Synfire's Guide to C++

5. Program Control

Here I will show you how to make your program repeat parts of code as many times as needed. This section will use comments to explain what is going on, I don't like going in too much on loops because they are fairly simple and it shouldn't take much to add them to your code. These programs will just print 10 'x's on the screen.

do{...}while() loops

dowhile.cpp
#include <iostream.h>

int main()
{
    // Count is created and set to 0
    int Count = 0;
    do // The loop starts
    {
     Count++; // Count is incremented (increased by 1)
     cout << "x"; // prints an x on the screen
    } 
    while (Count < 9); // tests to see if it needs to
                // start over again.
    return 0;
}
while(){...} loops

while.cpp
#include <iostream.h>

int main()
{
    int Count = 0; // Count is created and set to 0
    while (Count < 10) // Checks to see if Count is less than 10
    {          // if it is then the program repeats
     cout << "x";
     Count++; // this increases the value of Count by one
          // but 'Count--' would decrease the value by one
          // another thing is that if the '++' or '--' is
          // before the variable the variable is changed 
          // before the program goes to the next line
    }
    return 0;
}
for(;;;){...} loops

for.cpp
#include <iostream.h>

int main()
{
    int Count; // This time the Count variable is not given a
           // value
    for (Count = 0; Count < 10; Count++)
    { // Count is set to 0; Count is tested; Count is incremented
     cout << "x";
    }
    return 0;
}
goto loops

goto.cpp
#include <iostream.h>

/***************************************************************
* Goto is C++'s spaghetti code, I am showing you about it because
* it is part of C++ but I don't recommend that you use it for your
* looping because it makes hard to read codes.
***************************************************************/
int main()
{
    int Count = 0; // Creates Count and set it to 0
loop:   cout << "x"; // Sets a point for the program to start over at
    if (Count < 10) // Checks to see if Count is less than 10
    {
     Count++;
     goto loop; // takes you back to the 'loop: '
    }
    else
    {
     cout << " "; // prints a white space just for the hell of it
    }
    return 0;
}
That should be clear enough for you to learn from, Loops aren't all that hard, but are extremely important! Never under estimate the power of a well written loop!

;) lol . o O ( Sorry, I always wanted to say that! )

Summary
In this section you learned to make your programs repeat a block of code as long as a certain expression returns true.

< < < Lesson 4: Conditional Statements | Lesson 6: Functions > > >



Want some naughty smileys for your Yahoo messenger? Then look HERE.