Reputation: 128
public class Test {
public static void main (String args[]) {
int i = 0;
for (i = 0; i < 10; i++);
System.out.println(i + 4);
}
}
The output of the following code is 14.Why it is not 4?
And how can it be 14? Need some explanation
Thank you in advance...
Upvotes: 4
Views: 113
Reputation: 17132
for (i = 0; i < 10; i++);
This loop does nothing but incrementing i
by one, 10 times .
Then
System.out.println(i + 4);
evaluates to
System.out.println(10 + 4);
// output
14
If you drop the semi colon at the end of for (i = 0; i < 10; i++);
, you shall get
4
5
6
7
8
9
10
11
12
13
as an output.
Upvotes: 3
Reputation: 4156
System.out.println(i + 4);
will get evaluated and executed after for (i = 0; i < 10; i++);
statement is evaluated.
Result of for (i = 0; i < 10; i++);
will be 10
. The condition i < 10
will be true till i=9
which is the 10th iteration and in the 11th iteration i
will be 10
as i++
will be computed and here the i<10
condition fails. Now final value of i
will be 10
.
The next statement System.out.println(i + 4);
is evaluated which is i(=10)+4 = 14
Upvotes: 0
Reputation: 2169
See description in comments:
// Declare variable 'i' of type int and initiate it to 0
// 'i' value at this point 0;
int i = 0;
// Take variable 'i' and while it's less then 10 increment it by 1
// 'i' value after this point 10;
for (i = 0; i < 10; i++);
// Output to console the result of the above computation
// 'i' value after this point 14;
System.out.println(i + 4);
Upvotes: 0
Reputation: 48404
Simple.
i
by 10
without doing anything else (notice the ;
after the for
loop definition)System.out
statement prints i + 4
outside the loop (only once), i.e. 14
Upvotes: 3