Array Questions


Print all elements of an array

var arr = [10,21,23,11,2,1];
for(var i=0;i<arr.length;i++){
console.log(‘The value is ‘,arr[i]);
}

Find sum of all elements of array
var sum = 0;
for(var i=0;i<arr.length;i++){
sum = sum+arr[i];
}
console.log(‘The final sum is ‘,sum);
 
Find product of all elements of array
var p = 1;
for(var i=0;i<arr.length;i++){
p = p*arr[i];
}
console.log(‘The final product is ‘,p);

p=1;
//product of all even numbers inside array
for(var i=0;i<arr.length;i++){
if(arr[i]%2==0){
p = p*arr[i];
}
}
console.log(‘The final product of even numbers is ‘,p);

 

Sum of all digits

var n = 235;

var sum = 0;

while(n>0){ //235 , 23 , 2

   var r = parseInt(n%10); //5 , 3 , 2

   sum = sum + r; //5, 8 , 10

   n = parseInt(n/10); //23 , 2 , 0

}

console.log(‘The sum of digits’,sum );

Reverse a number

var n = 235;
var sum = 0;
while(n>0){//235 , 23 , 2
varr = parseInt(n%10);//5 , 3 , 2
sum = sum*10 + r; //5 , 53 ,532
n = parseInt(n/10); //23 , 2 , 0
}
console.log(‘The sum of digits’,sum ); //235

greatest number

   /*

greatest number

   */

var arr = [1,2,89,90,5,46,100,5];

var max;

for(var i=0;i<arr.length;i++){

if(i==0){

max = arr[i]; // assume the first number/ 0th index number is greatest

       }

else{

if(arr[i]>max){

max = arr[i];//2,89,90,100

           }

       }

   }

console.log(‘Max is ‘,max);

Array rotation

Problem :

Rotate an array by size n (n=3)

var arr = [1,2,3,4,5,6];

output : [4,5,6,1,2,3]

Solution :

var arr = [1,2,3,4,5,6,7];
let n = 3;//n is rotate by
let tmpArr = [];
var in1 = arr.indexOf(2);
console.log(‘The index of 2 is ‘,in1);
var j=0;
for(var i=in1+1;i<arr.length;i++){
tmpArr[j] = arr[i];
j++;
}
for(var i=0;i<=in1;i++){
tmpArr[j] = arr[i];
j++;
}
console.log(‘The new rotated array is ‘,tmpArr)

 

 

Site Footer