Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Oct 2011
    Posts
    27
    Thanks
    2
    Thanked 0 Times in 0 Posts

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

  • #2
    Banned
    Join Date
    Apr 2011
    Posts
    656
    Thanks
    14
    Thanked 69 Times in 69 Posts
    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.

  • #3
    Senior Coder alykins's Avatar
    Join Date
    Apr 2011
    Posts
    1,807
    Thanks
    41
    Thanked 199 Times in 198 Posts
    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
    }

    I code C hash-tag .Net
    Reference: W3C W3CWiki .Net Lib
    Validate: html CSS
    Debug: Chrome FireFox IE

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