-
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?
-
As your output suggests, it loops 3 times. If you want to see why, display the value of i each time as well.
-
Thanks I tried adding this but it says Cannot find symbol i
System.out.print( i );
Any thoughts?
-
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
}
-
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);
}
}
-
You forgot a curly brace somewhere.
-
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?
-
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
}
-
Ok got it to work, thanks. If I don't have the { } in there will it still execute 3 times? or once?
-
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.
-
Thanks for the input it helped and Ill remember to use the {} between my statements.
Thanks
-
You are welcom, please mark your thread solved with the thread tools if you aredone