1

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?

2
  • 2
    Note the semicolon after the for. Commented Apr 9, 2016 at 18:11
  • One of the best arguments I know for always using the opening and closing braces, even if it's a loop body with one line. IntelliJ would have caught this blooper. Commented Apr 9, 2016 at 18:18

3 Answers 3

6

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.