“The Power of Revision: Arrays S1”

Ankush Singh
2 min readMar 22, 2023

--

Rock n Roll 🚀

let arr and n, array and length respectively.

Print an Array :

function printArray ( arr, n )

for ( let i = 0 ; i ≤ n ; i++ )

console.log(arr[i])

Reverse an Array :

> start loop from n-1 index, to index 0 , i — — ;
> “ i ” should be greater than zero.
> tempArray [ ], we use a temporary array to hold the values of the original array in reversed order. This is often done because modifying the original array in place can cause unexpected behavior in certain programming languages.
> The push method adds one or more elements to the end of an array. For example:

function reverseArray( arr, n ){

let tempArray = [ ]

for(let i = n-1; i > 0 ; i — — ) {

tempArray.push(arr[i]) }

console.table(arr[i])

Largest three elements in an Array:

> Initialise the three elements, let first , second, third

> use Number.MIN_VALUE , assign the minimum value to these three variables alike, first = second = third = Number.MIN_VALUE
> current element = x or arr[i]

if (arr[i] > first)

{ third = second

second = first

first = x }

else if ( x > second && arr[i] != first){

third = second

second = arr[i]}

else if ( arr[i] > third && arr[i] != second){

third = arr[i]

}

//Print first, second, third

In the first case, the if statements within the for loop attempts to compare the current element with the three largest values and update the three largest values if necessary. The console.log statement at the end prints all three values.

In the second case, the if statement within the for loop attempts to compare the current element with the three largest values and update the three largest values if necessary. However, there is no additional if statement to update the third largest value after the first two largest values have been found. Therefore, the console.log statement only prints the first two largest values.

Sum all the elements of an Array :

> use variable sum with value = 0

> simple, sum = sum + arr[i]

function addup (arr, n){
let sum = 0;
for ( let i = 0; i< n-1; i++ ){
sum = sum + arr[i]
}
console.log( sum )
}

--

--

No responses yet