PDA

View Full Version : How do you figure out how many times this for loop iterates?

sabi
03-08-2012, 05:42 AM
How would you figure out how many times this for loop iterates? Instead of having to trace every step, is there another way finding out how many times a nested for loop will iterate?

for(row = 1; row <= 5; row++)
{
for(col = 1; col < row + 1; col++)
{
System.out.print("*");
}
System.out.println()
}

webdev1958
03-08-2012, 05:48 AM
1) initialise a counter variable to 0 just above the FOR loop.

2) incement the counter by 1 as the first step in the for loop

3) Then when the line in the FOR loop that triggers exiting the FOR loop is executed, the counter variable in 1) will contain how many times the loop iterated before exiting.

or

4) you can use the current value of col col when you exit the loop to calculate the number of iterations based on its min value and increment that you specified - just basic primary school arithmetic.

alykins
03-09-2012, 12:00 AM
it is going to go through the first loop 5 times- the second loop is going to go through 1 -> 5 times and it will print a star pattern

*
**
***
****
*****

I don't know why they start on 1, usually for loops are started on 0... if you ever get confused in a for loop w/ the <= crap, it is the same as the number on the right + 1 and a <... eg

for(int i=0; i <=4; i++){
loop will hit 5 times
}
this is the same as
for(int i=0; i<5; i++){
loop will hit 5 times
}