Back
Welcome to Intellipaat Community. Get your technical queries answered by top developers!
There are n numbers of ways to find the sum of array in Java some of them are mentioned below:
Method 1 : Using built-in reduce()
Example:
function all(arr) { if(!Array.isArray(arr)) return; return arr.reduce((a, v)=>a + v); }
function all(arr) {
if(!Array.isArray(arr)) return;
return arr.reduce((a, v)=>a + v);
}
Using for loop
function all(arr) { if(!Array.isArray(arr)) return; let totalNumber = 0; for (let i=0,l=arr.length; i<l; i++) { totalNumber+=arr[i]; } return totalNumber; }
let totalNumber = 0;
for (let i=0,l=arr.length; i<l; i++) {
totalNumber+=arr[i];
return totalNumber;
Using while loop
function all(arr) { if(!Array.isArray(arr)) return; let allnum = 0, i=-1; while (++i < arr.length) { allnum+=arr[i]; } return allnum; }
let allnum = 0, i=-1;
while (++i < arr.length) {
allnum+=arr[i];
return allnum;
31k questions
32.8k answers
501 comments
693 users