+ 2

Need help explain this..!

int i,sum=0 for(i=1; i<=5; i++) sum+=i; System.out.println(sum);

30th Apr 2017, 1:51 PM
SaNtO SaNdY☣
SaNtO SaNdY☣ - avatar
7 Answers
+ 4
yep tis can make output 6.
30th Apr 2017, 2:32 PM
SaNtO SaNdY☣
SaNtO SaNdY☣ - avatar
+ 3
the output is 6, how is this.? am not clear ..!
30th Apr 2017, 2:00 PM
SaNtO SaNdY☣
SaNtO SaNdY☣ - avatar
+ 3
but I have seen in challenge it's output is 6 that's y am ..???
30th Apr 2017, 2:20 PM
SaNtO SaNdY☣
SaNtO SaNdY☣ - avatar
+ 1
int i,sum=0 // define i and sum variable as int set sum to zero for(i=1; i<=5; i++) //loop from i=1 to i=5 increment is 1 per each //execution sum+=i; // sum=sum+i System.out.println(sum); // print the output
30th Apr 2017, 1:55 PM
Sagheb
Sagheb - avatar
+ 1
The output is 15. I also check this code and got 15.
30th Apr 2017, 2:18 PM
Sagheb
Sagheb - avatar
+ 1
I think in the for section was this: for(i=1; i<=5; i=i+4) and thats the only way you can get 6 as output
30th Apr 2017, 2:26 PM
Sagheb
Sagheb - avatar
+ 1
sum+=5; System.out.println(sum); Since there is no indentation after for loop line, these 2 statements are outside the for loop. at the end of the for loop value of i is 6. and adding i to the sum makes output is 6
30th Apr 2017, 5:46 PM
Mallikarjun Dodmani
Mallikarjun Dodmani - avatar