# Loop execution

Printable View

• 03-14-2011, 12:12 AM
tj_wolf2
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?
• 03-14-2011, 12:16 AM
Iron Lion
As your output suggests, it loops 3 times. If you want to see why, display the value of i each time as well.
• 03-14-2011, 12:21 AM
tj_wolf2
Thanks I tried adding this but it says Cannot find symbol i

System.out.print( i );

Any thoughts?
• 03-14-2011, 12:46 AM
sunde887
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.

Code:

```for(int i = 0; i < 5; i++){   //do stuff } if(condition){   //do stuff } else{   //do stuff }```
• 03-14-2011, 01:00 AM
tj_wolf2
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);
}

}
• 03-14-2011, 01:02 AM
sunde887
You forgot a curly brace somewhere.
• 03-14-2011, 01:06 AM
tj_wolf2
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?
• 03-14-2011, 01:11 AM
sunde887
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.

Code:

```for(int i; i < 5; i++){   //statemen 1   //statement 2 }```
• 03-14-2011, 01:16 AM
tj_wolf2
Ok got it to work, thanks. If I don't have the { } in there will it still execute 3 times? or once?
• 03-14-2011, 01:19 AM
sunde887
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.
• 03-14-2011, 01:23 AM
tj_wolf2
Thanks for the input it helped and Ill remember to use the {} between my statements.
Thanks
• 03-14-2011, 01:24 AM
sunde887
You are welcom, please mark your thread solved with the thread tools if you aredone