+1

# int sum = 0

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

3 Answers

New Answer

0

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

+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?

+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.