0

int sum = 0

in most of the codes i see sum is always equal to zero so why is that so

11th Apr 2019, 1:28 PM
William Benson
William Benson - avatar
5 Answers
- 1
It is often set to zero initially, because it serves as a variable slowly adding the rest of the numerical values. E.g. If you want the sum of 1,2,3,4,5 it would be: sum = 1+2+3+4+5. If you use any other initial value for sum, let's say 1, the sum would be calculated as 1+1+2+3+4+5
11th Apr 2019, 1:41 PM
Rasmus Bons
Rasmus Bons - avatar
+ 3
Just a quick quiz to see if you really understand now: Suppose now we are running loops to calculate the product of an array of numbers, What value should we initialize the variable for storing temp products as?
11th Apr 2019, 4:03 PM
Gordon
Gordon - avatar
+ 2
There is a good reason behind initializing sum to 0. So basically what is expected from a variable named in this manner might be to store the sum of a collection of data. So just assume you have a list with values - [1,2,3,4,5] and you want to get the sum. A classic way is iterating through all of the elements and add each number to the variable sum. So in runtime sum would undergo to changes like this sum = (((((1) + 2) + 3) + 4) + 5) //what i want to express with bracket are the iterations. And finally sum would store 15 in it. But we need to initialize it before using. If we initialized with 1 or another instead of 0 the sum would have a different value - in this case 16. #version Sum = 0 sum = 0 + (1+2+3+4+5) = 15 #version sum = 1 sum = 1 + (1+2+3+4+5) = 1 + 15 = 16 Hope you got it.
11th Apr 2019, 1:46 PM
Seniru
Seniru - avatar
0
(first sorry if my english was bad) Because, if you didn't assign number to your variable the compiler will generate random numbe for ex: try defining int and then do cout for it like int i; cout<<i; it will give you random number for that when U define int sum u need to assign it value to 0 for the compiler don't give it random number and add it to the numbers your are calculating more ex: int number=5 sum=0 later you will sum=number+sum this mean: 0=0+5 this = 5 I hope U know now why we always put sum=0 and counter put it to 1;
10th Apr 2020, 7:52 PM
Dany Saad
Dany Saad - avatar
- 1
the last explain is awesome,thanks very matchđŸ‘ŒđŸ»
14th Nov 2020, 12:10 AM
Aleks kryzhanivskyi
Aleks kryzhanivskyi - avatar