Folder101   Home Notes Quiz Assigns Info  
Forum Forum
101 Home 101
 
  C++ Level 2

Program Flow & Iteration Statements

Intro - Program Flow Control

For Loop

While Loop

Do-While Loop

Extension Work


  Intro- Program Flow Control

You have previously learnt how to control the flow of code execution by using selection statements like if-else and select-case.

Another way of controlling flow is through use of iteration statements (also called loops.) Loops allow the execution of a set of instructions to be performed over and over again until a certain condition is reached.  Just to summarize again:-

Selection statements are:-

  • If - Else
  • ? operator
  • Switch

Iteration statements are:-

  • For
  • While
  • Do-While

As you will see, the for statement allows a set of instructions to be executed a predetermined number of times. The do-while and while loops are more open-ended in that may not know when the condition that stops the loop will be reached.

We will start by looking at the 'for' iteration statement loop. 


  The For Statement

The general form of the for loop is as follows:-

for (initialization; condition; increment) statement sequence;

initialization;

This is generally an assignment statement used to set a loop control variable. e.g. i = 0. Here I have set the loop control variable to an initial value of 10.

condition;

To determine when the loop exits you need some kind of condition, This is a relational statement such as i < 10. This means loop until the value of i reaches 10.

increment

The increment defines how the loop control variable is changed each time the loop is repeated. e.g. i++; This means increase i by 1 every time the loop repeats.

Here it is in full, with each part separated by semi-colons:-

for (i = 0 ; i < 10; i++) statement sequence;

This means set the initial value of i to 0. Then execute the statement sequence. Loop and increment the value of i to 1. Check the condition (that i is still less than 10 which it is) and execute the statement sequence again, and so. The statement sequence is executed over and over again until i finally reaches the value of 10 when the condition is reached and the loop is broken.

To put it simply, the for loop continues to execute until the condition becomes false. Then program execution continues on any line following the the for loop.

Now let's have a more concrete example. Suppose I want a program to display ten lines of the two times table on screen. The easiest way would be to use a for loop.

for (int i = 1 ; i < 11; i++)  cout << i << " times 2 is " << (i * 2) << endl;

This prints out...

1 times 2 is 2
2 times 2 is 4
3 times 2 is 6
4 times 2 is 8
etc...

If I want more than one statement to be executed for every loop, all I have to do is enclose all the statements inside curly block brackets.

for (int k = 10 ; k > 0; k--)  {

cout << "The square of " << k << " is " << k*k<< endl;

cout<< ": The root of " << k<< " is " << sqrt(k) << "\n";

}

Just for a change I called my loop control variable k. If you want to run the code example above you will need to inlude the math.h library file for the sqrt function to be recognised.

Take note of the following points:-

  • This time, for every loop I am decreasing the value of the loop control variable k.
  • I declared k inside the for loop. If you declare a variable inside the for statement then it is not available for use anywhere else in your code apart from inside the for block. In other words it is local to the for block.

Here is another for loop example:-

int y;

cin >> y;

for (int x = 10; x<y; x += 2 )  {

cout << "You have " << k << " seconds left." << endl;

}

Take note of the following points:-

  • This loop may never execute at all if the user types in a value which sets y larger the 10. This is because in a for loop, the conditional check is always carried out first before entering the loop.
  • Also, this time x is incremented by 2 every time the for statement loops.

For Loop - Multiple Conditions

All the previous examples use a single loop control variable to control the loop. However, it is fairly common to use more than one loop control variable.  As an example:-

For Loop - Missing Statement Parts

It is often useful to create a for loop with a missing increment section. Useful if say you want a loop to keep repeating until the user enters a particular input character. For example:-

for (char x = 0; x!= 'q'; ) cin >> x;  

Here, the increment section of the for is missing. The loop will keep repeating until the user enters the character q.

You can miss out other parts of the for loop statement. For example you may want to initialize the for loop outside the loop itself. In the following for loop, the loop control variable countdown is initialized outside the for statement in order to get the user's input first.

int countdown;
cin >> countdown;
for ( ; countdown> 0 ; ) {
      countdown--;
     cout << countdown;
}

On running this, if I enter the number 6, I get...

For Loop - Infinite Loop

At some point in your programming activities you will probably create an infinite loop by accident, perhaps by incorrectly specifying the loop condition or because of an error in your logic.  However, if you want to create an infinite for loop - here's how.

for ( ;  ; ) cout << "stop me if you can\n";

Although this loop will run forever if allowed, you could insert a break statement somewhere in the loop body to stop the loop:-

char ch = '\0';
for ( ; ; ) {
     cout << "please enter a character, or press q to quit\n";
     cin >> ch;
     if ( ch == 'q' ) break;
}

For Loop - No Body

for (int x = 0; x< 10; x++) ;

You could use a for loop without a body to create some kind of time delay.  Here is an example:-

for (long t = 0; t< 1000000; t++) ;

Although this may be useful on occasion - remember that your code may be run on different speed computers and this will not loop for the same period of time on each one. Look at the example below, I added extra code to see how long the for loop above runs on my PC.

#include <time.h>

void main() {
time_t stime = time(NULL);
for (long t = 0; t< 1000000000; t++) ;
     time_t etime = time(NULL);
     cout << "time taken to loop was " << difftime(etime,stime) << " seconds";
}

The output was:-

You will probably get a different result.

~Now try the activity~

Activity 9A

  Here is a cute little for loop

for (char ch = '\0'; ch != 'q'; ) {
    cout << "choose a piglet number from 1 to 5 or q to quit\n";
    cin >> ch;
    switch (ch){
        case '1':
            cout << "This little pig went to the market.\n\n";
            break;
        case '2':
            cout << "This little pig stayed home.\n\n";
            break;
        case '3':
            cout << "This little pig had roast beef.\n\n";
            break;
        case '4':
            cout << "This little pig had none.\n\n";
            break;
        case '5':
            cout << "And this little pig went\n\t\tWee, wee, wee, wee, all the way home.\n\n";
            break;
        default:
            break;
    }
}

Now create a different version of this for loop where a single line of the rhyme is printed out for each repeat of the loop. Also, ask the user if they want to see the next line or quit every time. The program output should be similar to...


  While Loop

A while loop is similar to a for loop in that the condition for looping is checked at the start of the loop, before entering it. The general form of the while loop is as follows:-

While (condition is true ) {

statement sequence;

}

Unlike the for loop, there is no loop control variable or increment section. The condition of a while loop may be any expression and the statement or set of statements inside the loop body will execute repeatedly while the condition evaluates to true ( any non-zero value). When the condition is false, the next line of code after the loop is executed.

Here is an example of a function that returns the length of a string. Remember that the string is represented as an array of characters terminated by a null character '\0'.

int str_len(char string[]) {

int i = 0;

while (string[i] != '\0') i++;

return(i);

}

You could call this function from main and pass it any string to get the string's length. I.e. typing the following in main..

cout << "The string length of " << ch << " is " << str_len(ch) << endl;

...would produce...

Or you could get the string length of a user's input:-

char ch[80];
cin >> ch;
cout << "The string length of " << ch << " is " << str_len(ch) << endl;

Of course, you know that C++ has it's own string length function called strlen which does the same job.

Just like the for loop, there are many ways of using a while loop.

You can create a while loop that loops repeatedly until the user presses a particular key:-

char ch;
while ( (ch=getchar()) != 'q' );

You can create an infinite loop:-

while (1 );

This would loop forever because the value (1) is always true. To make this more useful and to stop it looping forever, you could add a break statement inside the loop body somewhere:-

while (1 ) {

if (ch=getchar() == 'q' ) break;

}

This does the same job of looping until the user presses the q key.

Sometimes you may need to create your own loop control variable. In the following code the variable that controls the loop is called countdown:-

int countdown = 10;

while (countdown) {

  cout << countdown << " ";

  countdown--;

}

This is a while version of the countdown code shown previously using a for loop. The loop will repeats until the variable countdown reaches 0.

The output is..

~Now try the activity~

Activity 9B

Create a simple program that accepts user input and then adds spaces to the end until the string is a certain length, say 10. To start you off...

void main() {

   char str[255];

      cout << "enter something";

   cin >> str;

   int len = strlen(str);

//now using a while loop, add spaces to the end of the string if it is less than 10 characters long.

}


  Do-While Loop

The general form of the do-while loop is as follows:-

do {

statement sequence;

}(condition is true ) while

The do-while loop iterates until the condition at the bottom because false. However, because the condition is not checked until the bottom of the loop, this means the do-while loop always executes at least once.

This is different to the for and while loops which check the condition at the top of the loop and need never execute at all if the condition is initially false.

char num;

do {

cout << "Enter number from 1 to 9:";

cin >> num;

} while ((num<'1') || (num>'9'));

cout << "You chose " << num << endl;

If I run it ...     

It is not perfect though because the user could enter more than one character an the program will just pick up the first character. I.e.

The code could be refined to check for the string length of the user's input. I.e.

char num[2];

do {

cout << "Enter number from 1 to 9:";

cin >> num;

} while ((num[0]<'1') || (num[0]>'9') || strlen(num) != 1);

cout << "You chose " << num << endl;

Here is a final useful example that displays a menu to the user and loops until they press the q key.

void main () {

char ch;

do {

cout << "Select 1 for a short, back and sides\n";
cout << "Select 2 for a completely bald look\n";
cout << "Select 3 for a completely headless look\nor press q to quit\n ";
cin >> ch;

switch(ch) {

case '1':
    shortBackSides();
    break;
case '2':
   baldLook();
    break;
case '3':
    headlessLook();
    break;
default:
    displayError();
    break;
}

} while (ch != '1' && ch != '1' && ch != '1' && ch != 'q');

}

~Now try the activity~

Activity 9C

  1. Add a do-while loop to the program code below whicht prompts a user for a password so it continues to prompt until either a valid password is given or until they press q to cancel.

void main() {

   char passwords[4][20] = {"secret", "mystery", "sesame", "user"};

   int res = 1;

   char usrInput[255];

   cout << "please enter your password\n";

   cin >> usrInput;

   for (int i=0; i < 4; i++){

       if(res) res = strcmp(usrInput,passwords[i]);

   }

}

note: strcmp returns a 0 on a successful match


  Extension Work

Carry out the following exercises:-

  1. Now start step9 of the practice assignment 3

That's it!