What is wrong with this code guys? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is wrong with this code guys?

for(int i=0;i<10;i++){ int sum; sum=sum+i; } System. out.println("sum is:" + sum); //I think problem is here na guys.

16th Oct 2017, 8:19 AM
Code Race
Code Race - avatar
1 Answer
+ 5
The problem is that you declare sum inside the for loop, it gets destroyed when it reaches the end of the for loop, thus sum does not exist outside the for loop. You should declare sum before the for loop and initialize it to 0.
16th Oct 2017, 8:28 AM
Dennis
Dennis - avatar