0
program to calculate sum of any number of arguments
I have been trying to solve this problem wherein any number of arguments can be passed and the program has to calculate the sum of all the numbers passed. Can you please help me understand what mistake am I making? //complete the function function Add(...nums){ let sum = 0; for (let num of nums){ return sum += num; } } console.log(Add(1,2,3)); console.log(Add(4,14,5,9,14)); console.log(Add(2,36));
9 Réponses
+ 3
CHANDAN ROY
Don't return sum inside loop. Return outside the loop. Because after first iteration loop will break.
+ 3
CHANDAN ROY
I said return sum not whole thing.
+ 3
CHANDAN ROY
I can solve but you have to understand what I am saying.
+ 2
CHANDAN ROY It will work. Show me how you are doing.
+ 2
Got it sir. I misunderstood. Now it's clear. Thanks a lot sir
+ 1
I got it sir. Thanks for letting me understand from my mistakes and guiding me out of it.
+ 1
Function Add(...nums){
Let sum=0;
For(let num of nums){
Sum+=num;
}
Return sum;
}
0
Can you please solve it? Because returning outside of loop is not working.
0
As you suggested, I have changed it to return sum outside the for loop
//complete the function
function Add(...nums){
let sum = 0;
for (let num of nums){
}
return sum += num;
}
console.log(Add(1,2,3));
console.log(Add(4,14,5,9,14));
console.log(Add(2,36));