Reputation: 55
PrintStream out = System.out;
int sum = 0;
for(int i = 0; i<5; i++)
for(int j=i; j<5; j++)
sum++;
out.println(sum);
outputs: 15. i dont know how this gets 15. i tried solving it in my head, i keep getting 25.
If we ignore the second for loop, and put sum++ in the first for loop, you get 5. But how do we get 15 from the 2nd for loop?
PrintStream out = System.out;
int sum = 0;
for(int i = 0; i<5; i++)
for(int j=i; j<5; j++);
sum++;
out.println(sum);
outputs: 1. What happens if you put ; after for statement. does it stop?
Upvotes: 1
Views: 3069
Reputation: 328598
i = 0 => j goes from 0 to 4 => sum = 5
i = 1 => j goes from 1 to 4 => sum = 5 + 4 = 9
i = 2 => j goes from 2 to 4 => sum = 9 + 3 = 12
i = 3 => j goes from 3 to 4 => sum = 12 + 2 = 14
i = 4 => j goes from 4 to 4 => sum = 14 + 1 = 15
your second code snippet does not compile as it is.
EDIT
Now that your second snippet compiles:
for(int i = 0; i<5; i++)
for(int j=i; j<5; j++);
sum++;
is equivalent to (and this is why you should always use braces):
for(int i = 0; i<5; i++) {
for(int j=i; j<5; j++) {
}
}
sum++;
That explains why it outputs 1.
Upvotes: 6
Reputation: 59607
The loop is basically creating a triangular number, specifically the 5th triangular number, e.g. a number of the form n + (n - 1) + ... + 2 + 1
.
The trick, and the reason that you don't see 25 as the result, is in the second loop: it only iterates from the current value of i
up to 5
.
On each iteration of the inner loop the sum is incremented once. Because of the loop trick, the inner loop iterates 5 times, then 4, and so on:
first iteration of the outer loop: j = 0 to 4 -> 5 increments
second iteration of the outer loop: j = 1 to 4 -> 4 increments
... 3 increments
... 2 increments
... 1 increment
5 + 4 + 3 + 2 + 1 = 15
Upvotes: 0
Reputation: 783
To get 25, instead of
for(int j=i j<5; j++); // inner loop
sum++;
use
//......here
for(int j=0 j<5; j++); // inner loop
sum++;
What you are doing now is
(1+1+1+1+1) + (1+1+1+1) + (1+1+1) + (1+1) + (1)
whereas what you want is (1+1+1+1+1).. 5 times
p.s. why the loop in the second code is for(int j=il j<5; j++);
? il
is not defined, and it 'll stop at the ;
even if you have defined il
somewhere earlier.
Upvotes: 0
Reputation: 22692
The output is 15 because j
is initialized to the value of i
in each iteration of the first loop.
The output would be 25 if j
was initialized to zero in stead.
Upvotes: 0