Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 03-08-2012, 04:42 AM   PM User | #1
sabi
New Coder

 
Join Date: Oct 2011
Posts: 27
Thanks: 2
Thanked 0 Times in 0 Posts
sabi is an unknown quantity at this point
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()
}
sabi is offline   Reply With Quote
Old 03-08-2012, 04:48 AM   PM User | #2
webdev1958
Banned

 
Join Date: Apr 2011
Posts: 656
Thanks: 14
Thanked 69 Times in 69 Posts
webdev1958 can only hope to improve
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.

Last edited by webdev1958; 03-08-2012 at 05:28 AM..
webdev1958 is offline   Reply With Quote
Old 03-08-2012, 11:00 PM   PM User | #3
alykins
Senior Coder

 
alykins's Avatar
 
Join Date: Apr 2011
Posts: 1,608
Thanks: 37
Thanked 183 Times in 182 Posts
alykins will become famous soon enough
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
Quote:
*
**
***
****
*****
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
}
__________________

I code C hash-tag .Net
Reference: W3C W3CWiki .Net Lib
Validate: html CSS
Debug: Chrome FireFox IE
alykins is offline   Reply With Quote
Users who have thanked alykins for this post:
sabi (03-09-2012)
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 03:04 PM.


Advertisement
Log in to turn off these ads.