1. Member
Join Date
Mar 2011
Posts
13
Rep Power
0

## Loop execution

How many times does the following loop iterate? Explain.

int j = 0;
for(int i = 1; i <= 120; i = i*5)
j = j+1;

When I write it in and have it print something out I only get 1 exectution, but am I missing something is it 1 or 3 times? I can have it out put j and it equals 3, but I'm just a little confused can some one explain?

2. Senior Member
Join Date
Nov 2010
Posts
210
Rep Power
7
As your output suggests, it loops 3 times. If you want to see why, display the value of i each time as well.

3. Member
Join Date
Mar 2011
Posts
13
Rep Power
0
Thanks I tried adding this but it says Cannot find symbol i

System.out.print( i );

Any thoughts?

4. loops, if else blocks and lots of other flow control only takes one statement. If you want more than one statement(for example, a print line and some operation), you need to wrap it in {}, you should get into the habit of using {} on all flow control structures so you don't forget them.

Java Code:
for(int i = 0; i < 5; i++){
//do stuff
}
if(condition){
//do stuff
}
else{
//do stuff
}

5. Member
Join Date
Mar 2011
Posts
13
Rep Power
0
why doesnt this work?

public class midterm
{
public static void main(String[] args) {

int j = 0;
for(int i = 1; i <= 120; i = i*5)
j = j+1;
System.out.println(i);
}

}

6. You forgot a curly brace somewhere.

7. Member
Join Date
Mar 2011
Posts
13
Rep Power
0
it says (i) cannot be found? if I take out the j = j+1 it says
1
5
25
but with it in it does work so I guess back to the original with the j = j+1 does it only loop once?

8. It has to do with your missing curly brace. Since a variable declared in the loop "dies" outside the loop statement it is not seen. If you wrap the statements in the loops statement block it will find i.

Java Code:
for(int i; i < 5; i++){
//statemen 1
//statement 2
}

9. Member
Join Date
Mar 2011
Posts
13
Rep Power
0
Ok got it to work, thanks. If I don't have the { } in there will it still execute 3 times? or once?

10. It will still execute 3 times. The difference between {} and not having them is just what gets executed each pass through the loop. If they are there it can execute many statements per loop, if they are not there only one statement will be executed each time it loops.

11. Member
Join Date
Mar 2011
Posts
13
Rep Power
0
Thanks for the input it helped and Ill remember to use the {} between my statements.
Thanks