0
How this java code work. How Java understand to totalize numbers from 0 to 10?
Class calcultionofsum{public static void main(String args []) {int n = 10; int sum = 0; while (n>0) sum += n--; system.out.println(sum);}}
4 Answers
+ 5
Here's how it works:
The n variable is initialized to 10.
The sum variable is initialized to 0.
The while loop will run as long as n is greater than 0.
In each iteration of the loop, sum is incremented by n and then n is decremented by 1 (using the post-decrement operator --).
When n reaches 0, the loop will stop.
Finally, the sum is printed.
So, the loop will run 10 times, adding the numbers 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 to sum. The sum of these numbers is 55, so that's the value that will be printed by the code.
+ 2
sum = sum + n--;
sum = 0 + 10; now n = 9
sum = 10 + 9;
sum = 10 + 9 + 8 ;
sum = 10 + 9 + 8 + 7;
sum = 10 + 9 + 8 + ....... + 2 + 1
sum = 55;
+ 2
This is really basic stuff, you want to go through some of the courses which will explain the concepts betterâŚ
1) Two variables, n - which is 10 and sum - to hold the âtotalizeâ - your words :)
2) A while loop, while 10 is greater than 0 - the value is added to the sum variable.
3) The n variable is then decremented by one (so the conditional check in the while loop stops when n is zero).
+ 1
⌠may be easier to understand:
While 10 > 0
n = 10
n greater than zero
sum + 10
n - 1
n = 9
n greater than zero
sum + 9
n - 1
etc
âŚ.
âŚ.
âŚ.
n = 1
n greater than 0
sum + 1
n - 1
n = 0
n not greater than 0
loop stops.