CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9
  1. #1
    Join Date
    Oct 2010
    Posts
    4

    Variable loop help

    Hi all,

    I'm new to programming and am struggling a bit with this "while" and "for" loop. What I'm struggling with is where to sub in what numbers for the variables of "count" and "i".

    What would really help is if someone could run this loop 2 or 3 times inputting the relevant numbers for the variables as from there I could get some clarification on which values should be where and the path to follow for future loops:


    int count = 0

    while (count<10)
    {
    count=count+1;
    }


    for int 1 = 0; i < 5; i++
    }
    count = count - 1;
    }
    MessageBox.Show("The answer is "+count);
    }



    Really appreciate any help anyone could offer?

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Variable loop help

    The first loop will iterate 10 times.

    The second loop (which isn't even valid code and would not compile) will take 'count' down to 5.

    What is the question here exactly?

  3. #3
    Join Date
    Oct 2010
    Posts
    4

    Re: Variable loop help

    Hi there,

    Thanks for replying.

    That code is from a text book I'm currently learning from, so I'm not sure if it's necessarily been designed to be compiled or simply act as an example for the purpose of explaining loops.

    My question is I'm looking for some help with exactly which value goes in where when the loop is run. Am I right that with the first loop, if it were run 10 times it would be:

    Count = 0+1, count=1+1, count =2+1 etc etc until a total of 9 is reached?

    It's the 2nd part of the "for" loop that I'm struggling with? I just need to see a few runs of the loop with the figures entered in where the variables are to understand how it is calculated and the order in which the calculation is performed?

    Can you help?

  4. #4
    Join Date
    May 2009
    Location
    Bengaluru, India
    Posts
    460

    Re: Variable loop help

    the second "For" loop gets run for 5 times and count value will get reduced from 9 to 4 after getting decremented 5 times..

  5. #5
    Join Date
    Oct 2010
    Posts
    4

    Re: Variable loop help

    Sorry,

    I've just noticed an actual error in my typing of the code. In the "for" part "i" should be equal to 0 so it should read:

    int i=0

    and not:

    1=0

    So the 2nd part should read:

    for int i = 0; i < 5; i++
    }
    count = count - 1;
    }
    MessageBox.Show("The answer is "+count);
    }

  6. #6
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Variable loop help

    OK. This is the correct syntax:
    Code:
    for (int i = 0; i < 5; i++)
    {
        // loop body goes here...
    }
    The things to note are (in the order in which they appear in the loop's "header"):
    1) The declaration (and) initialization of the loop variable,
    2) The condition - must evaluate to true in order for the loop to run,
    3) The "loop expression" - executed at the end of the each iteration.

    for (int i = 0; i < 5; i++)

    So typically you declare a loop variable, traditionally named i for the most of the time, and initialize it to some value, like 0, or to whatever value the situation might demand.
    Then you set the loop condition, which is evaluated before each iteration; the loop body executes only if the condition is true. The last, but not the least, is the so-called loop expression, which can be really anything, but is generally used to increment the loop variable, since it's automatically executed after each iteration.
    (The i++ is the postfix increment operator - it increments the value of i by one.)

    Note that these can be omitted. For example, the following statement is valid, but not of much use since all it would do is loop forever - generally not a good thing.
    Code:
    for (;;)
    {
        // whatever...
    }
    You can omit, for example, the initialization of the loop variable if the variable that will be used was defined before and used with some different purpose. Or you can use it to reassign a value to an already declared variable.
    Code:
    int i = aSprite.CurrentFrame;   // a contrived example
    //...
    // now reuse i for something else
    for(i=0; i < max; i++)
    {
        //...
    }
    Omitting the condition generally isn't of much use.
    The final expression can be relocated inside the loop body, or can be omitted in such cases where the execution of something inside the loop body would eventually lead to the condition evaluating false. But, you can put more or less anything in there. For example, in a console application, something like this would print 'Hi!' five times:
    Code:
    for (int i=5; i > 0; Console.WriteLine("Hi!"))
         i = i - 1;
    Note that if the loop body consists of a single statement, you can omit the {}.

    P.S. Please use the [code][/code] tags when posting code - preserves formatting.
    Last edited by TheGreatCthulhu; October 4th, 2010 at 06:29 PM.

  7. #7
    Join Date
    Oct 2010
    Posts
    4

    Re: Variable loop help

    Hi,

    Thanks for taking the time to reply to me in such detail.

    I understand each loop on it's own, what Im struggling with though is how they work together and the order of things.

    Does the first loop keep repeating until "count" is equal to 9 (as far as "count" can go without being equal to or more than 10), and then you move onto the 2nd part which would run 4 times (as far as "i" could run without being equal to or more than 5) subtracting 1 each time from "count" which starts off as 9 from the first part ("while loop")?

  8. #8
    Join Date
    Dec 2007
    Posts
    234

    Re: Variable loop help

    The second loop will run 5 times... the counter doesn't get incremented until the end of the loop. So on the first pass, i will be 0, but it will still subtract 1 from counter... making it 8... and so on.
    0->1 -- First Loop (counter =8)
    1->2 -- Second Loop (counter (=7)
    2->3 -- Third (counter = 6)
    3->4 -- Fourth (counter =5)
    4->5 -- Fifth (counter =4)

    The result at the end is that counter is 4.

    -tg
    * I don't respond to private requests for help. It's not conducive to the general learning of others.-I also subscribe to all threads I participate, so there's no need to pm when there's an update.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help - how to remove eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to???
    * On Error Resume Next is error ignoring, not error handling(tm). * Use Offensive Programming, not Defensive Programming.
    "There is a major problem with your code, and VB wants to tell you what it is.. but you have decided to put your fingers in your ears and shout 'I'm not listening!'" - si_the_geek on using OERN
    MVP '06-'10

  9. #9
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Variable loop help

    @Yetirat:
    Well, the first thing to do is to correct the code so that it can compile with no errors. In my previous post, I've shown you how the second loop should look.

    Then you can do two things, and it would be best if you went and did them both:
    • Pretend you're the CPU and execute the code in your head (or with the help of this super-secret ultra uber hi-tech tool called paper). You start with count=0 and go from there into the first iteration of the first loop, execute the loop's body, and then check if the condition still holds to see if there should be another iteration. If not - onto the next loop, and do the same thing.
    • Set a breakpoint wherever the count variable appears in your code - position the cursor there and hit F9 - a big red dot appears on the left. Then, when all set, hit F5 to start debugging (or click Debug>Start_Debugging, or click an inconspicuous green arrow somewhere in the menu). This will run the app, until it gets to the breakpoint (the "big red dot"-thing), and then it will stop allowing you to check the value of the variable by simply pointing the mouse at it (and maybe holding it in place for a moment). Now, that's before that line it broke on was executed. Then simply press F10 to step over - basically to execute the next line (line-by-line), and hover the mouse again to see what's changed.
      See? Debugging is no biggie! Don't forget to compare what you expected to happen with what actually happened.


    If you're willing to do what I've suggested, you'll answer your own questions and you'll gain more insight and better understanding.
    (It might also help if you read my previous post with more attention )
    Last edited by TheGreatCthulhu; October 8th, 2010 at 04:27 PM.

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured