Abdalrahman Gamal
Abdalrahman Gamal

Reputation: 23

Can someone explain what this Java code does?

I study Java as a subject in college and I got this code in the sheet to get the output, I executed the code to get the result of (11).

int i;  
for (i=1; i<10; i+=2);
System.out.println(i);

But what does it really do?

Upvotes: 1

Views: 146

Answers (3)

Charlie Martin
Charlie Martin

Reputation: 112356

Someone is being sneaky. Here's how it would lay out indented norrmally:

int i; 
for (i=1; i<10; i+=2)
    ; 
System.out.println(i);

int i; declares a variable named i of type int.

for (i=1; i<10; i+=2)
    ; 

is a for loop that starts by setting i to 1, and then loops while i is less than 10, adding 2 toi` each time. The semicolon after the for is a no-op, an empty statement.

Try this version and see what happens:

int i; 
for (i=1; i<10; i+=2)
    System.out.println(i); 
System.out.println(i);

Upvotes: 1

nhouser9
nhouser9

Reputation: 6780

The code could be written more clearly like this (I will include comments denoting what each section does):

//declare a number variable
int i;

//this is a for loop
//the first part sets i to 1 to begin with
//the last part adds 2 to i each time
//and the middle part tells it how many times to execute
//in this case until i is no longer less than 10
for (i = 1; i < 10; i+=2);

//this prints out the final value, which is 11
System.out.println(i);

So your code will start i at 1 and then loop i = 3, i = 5, etc. until i is no longer less than 10 which happens when i = 9, i = 11 Then the program stops and you print the final value of i

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201409

Let's start at the beginning, declare a variable named i of type int.

int i; 

Now we shall loop, initialize i to the value 1, while i is less than 10 add 2 to i (1, 3, 5, 7, 9, 11). 11 is not less than 10 so stop looping.

for (i=1; i<10; i+=2); 

Finally, print i (11).

System.out.println(i);

Upvotes: 6

Related Questions