Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: How do you figure out how many times this for loop iterates?

1. ## How do you figure out how many times this for loop iterates?

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()
}

• 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.

• 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
Code:
```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
}```

• ## Users who have thanked alykins for this post:

sabi (03-09-2012)

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•