In: Computer Science
Sum all the elements in the two-dimensional array below. Print
the
// result to the console.
var arr = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
javascript
The javascript code to get the sum of elements of array arr is:
//Declaring and initializing a 2D array
var arr= [[1,2,3],
[4,5,6],
[7,8,9]];
//Initializing a variable sum to store the sum of elements of array
var sum=0;
//Using two layer for loop to traverse through all rows,columns of array
for(var i=0;i<3;i++){
for(var j=0;j<3;j++){
//Adding array elements to variable sum
sum+=arr[i][j];
}
}
//Printing variable sum which contain the sum
//of all elements of array arr
console.log(sum);
I have used two layer for loop to traverse through every element of all rows,columns in the array. First for loop is for row reference, second for loop is for column reference. I have provided comments in the program explaining the lines of code.
I have tested the code and it is working fine. I am sharing a output screenshot for your reference:
Hope the answer helps you.
Thank you :)