-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem-6_Sum_of_All_Numbers_in_an_Array.js
More file actions
41 lines (31 loc) · 1.5 KB
/
Problem-6_Sum_of_All_Numbers_in_an_Array.js
File metadata and controls
41 lines (31 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Problem-6_Sum_of_All_Numbers_in_an_Array with Solution, Explanation, Verification, and Execution:
// To get sum of all numbers in an array, we can implement the Solution like below:
// -------------------------------------------------------------------
function sumArray(numbers) {
let total = 0;
let index = 0;
while (index < numbers.length) {
total += numbers[index];
index++;
}
return total;
}
// Explanation:
// ---------------
// The function initializes a total variable to zero and an index to track position. It uses a while loop to traverse the array, adding each element at the current index to the total and then incrementing the index. The loop continues until the index reaches the array's length. This methodical accumulation provides a basic summation without array methods like reduce, emphasizing incremental addition.
// Verification:
// ----------------
// function sumArray(numbers) {
// let total = 0;
// let index = 0;
// while (index < numbers.length) {
// total += numbers[index];
// index++;
// }
// return total;
// }
// console.log(sumArray([1, 2, 3, 4]));
// Execution of the above code block in IDE environment with node.js installed:
// ----------------------------------------------------------------------
// Input (In the directory in IDE environment with node.js installed): 'node Problem-6_Sum_of_All_Numbers_in_an_Array.js'
// Output (In the directory in IDE environment with node.js installed): [1, 2, 3, 4]