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

03-08-2012, 04: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++)

03-08-2012, 04: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.


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.

03-08-2012, 11:00 PM
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

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum