2 more for loops

This is a discussion on 2 more for loops within the C++ Programming forums, part of the General Programming Boards category; here is what i have: Code: char Let = 'J'; int Bo = -3; for (char Ind=Let; Ind<= 'J'; ++Ind) ...

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    17

    2 more for loops

    here is what i have:

    Code:
    char Let = 'J';
    int Bo = -3;
    
    for (char Ind=Let; Ind<= 'J'; ++Ind) <statement>;
    
    for (int Boun=1; Boun>=Bo;  --Boun) <statement>;
    for the 1st one i dont think it will run at all since Ind=Let and Let is 'J' that makes Ind 'J' so in the next part where Ind<= 'J' he is already less the or = to 'J' since his is 'J' so the loop should run at all correct?

    the 2nd one the statement should run 4 times until Boun is >=Bo correct?

    thanks

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Once and five times, respectively. Think about what equality means.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    17
    i can see why the 1st one is run once but why the second 5 times and not 4? if i have 1 and want to get to -3 i would just run it 4 time wouldnt i?

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  5. #5
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    Quote Originally Posted by newbie101
    here is what i have:

    Code:
    int Bo = -3;
    
    for (int Boun=1; Boun>=Bo;  --Boun) <statement>;
    Initial Pass: Bound = 1 (> -3)
    2nd pass: Bound = 0 (> -3)
    3rd pass: Bound = -1(> -3)
    4th: Bound =-2 (>-3)
    5th: Bound = -3, bo = -3 (still bound >= Bo, so we do it one more time
    finally: Bound = -4

  6. #6
    Registered User
    Join Date
    May 2006
    Posts
    17
    thanks got it

  7. #7
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    But your approach to for loops is kind of counter intuitive, generally if you want to execute a loop a certain (n) number of times, you would start at 0 and end at less than, or not equal to n, for example

    Code:
    for(int i = 0; i < n; i++)
      <statement>;
    
    or
    
    
    for(int i = 0; i != n; ++i)
      <statement>;
    Why start at 0? I guess goes back to basic computre fundamentals and ho memory is referenced.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21