# Thread: why does this only loop 2 times ?

1. Member
Join Date
Jan 2017
Posts
1
Rep Power
0

## why does this only loop 2 times ?

for (int i = 2; i < 10; i = i*i) {
System.out.println(i);
}

The answer i was given was 2 but shouldn't it be 3 times?

2
4 (2*2)
8 (4*2)

Doesn't a loop always begin with the first number?

2. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
13

## Re: why does this only loop 2 times ?

Go thru the loop by hand and write the values. Think about i*i.

Regards,
Jim

3. Senior Member
Join Date
Sep 2014
Location
MA, USA
Posts
398
Rep Power
6

## Re: why does this only loop 2 times ?

Originally Posted by jim829
How many different values can i have?

4. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
13

## Re: why does this only loop 2 times ?

Are you asking me? Actually, the OP should answer that question. And he did his calculations wrong anyway, which is why I suggested he focus on i*i.

Regards,
Jim

5. Senior Member
Join Date
Sep 2014
Location
MA, USA
Posts
398
Rep Power
6

## Re: why does this only loop 2 times ?

Originally Posted by jim829
Nope, that was a question for the OP. I figured you saw the bug right away.

6. ## Re: why does this only loop 2 times ?

What was printed when the loop executed?
What would be the value of i*i at the end of the second loop?

7. ## Re: why does this only loop 2 times ?

Also posted at: https://coderanch.com/t/675145/java/...s-JAVA#3161603