+ 1
why don't we write int sum ; instead of int sum =0 ; what does the zero does anyways ?
i tried running the code with each one , i see no difference
6 Respuestas
+ 8
When you write
int sum;
It means you declared variable 'sum' with some garbage value.
Garbage value is some random value which the variable holds.
It can be negative, positive or even zero. Declaring variables without initialization lead to logical errors which are hard to debug sometimes.
So to avoid this, we write it like this
int sum = 0;
We declared variable 'sum' and initializated it to 0 to avoid any error.
+ 4
Let's say you need to find factorial of number n
//You would declare variable like:
int fact, n;
cin >> n; //Thats OK, 'n' got some value by user
for(int i = 1; i <= n; i++) {
fact *= i;
//Now this statement is wrong.
//Let's see how
}
Suppose 'fact' has some garbage value 20.
n = 3
Factorial(3) = 6
Now let's dry run the code based on the given conditions above.
i = 1, i <= n (True)
fact *= i ----> 20 *= 1 ----> fact = 20
i = 2, i <= n (True)
fact *= i ----> 20 *= 2 ----> fact = 40
i = 3, i <= n (True)
fact *= i ----> 40 *= 3 ----> fact = 120
i = 4, i <= n (False)
//Loop terminated
Finally 'fact' will have 120.
Instead if you have initialized it to 1, you would have got the correct answer.
It is quite possible that you declare variable and forget to initialize it later.
This could lead to errors which are hard to catch most of times.
That's why it is considered a good practice to initialize variables at the time of their declaration.
+ 2
Initialize, if you write
int sum;
int num=1;
sum+=num;
That won't work.
+ 2
Thank you all , i got it
+ 1
Wait , but sum will be identified later by the user or by an equation in the code , still don't get it!
0
Now i am not so skillful in coding, but I guess I can explain this ;
Let us say we have a program and we a loop statement in it, lets assume a 'for' loop. Now as we know in loop we need to satisfy some conditions and perform some calculations again and again.
Lets say we use [ int sum;], and during first time computing the conditions we have a value and save it in 'sum'.
Now, compiler will run that loop second time and some value came that we need to store again in 'sum'. But since we need to add this value in the first value we have to use [ sum=sum+(some value lets say 20)],
Here is the confusing part:
If we wanna add both the values we calculated in sum, we need
'sum(new value)=sum(old value )+(new result)'
And if we use this, we have to keep in mind that compiler will use same process in very first loop, i.e,
'Sum(new value)=sum(old value)+(new result)
Here,
New result is our very first calculation.
Sum(new value) is the first value of sum will will obtain
Sum(old value),,,, ops! We don't have any value :(
That's why we fool the equation by talking a garbage value (i.e 0) to make the equation legit!