Learn to do stuff

Home  » Browse  » Learn to program in C++

 
Learn to program in C++
Posted July 31, 2006. Written by John Zervos, author of the text Byte Into C++ (2002). Tertiary Press: Melbourne.
This article provides a comprehensive yet simple to understand treatment of the C++ language for beginners. The article is divided into a series of separate lessons as follows:

Lesson 1 - Introduction
Lesson 2 - Data types and variables
Lesson 3 - Operators
Lesson 4 - Selection
Lesson 5 - Iteration
Lesson 6 - Functions


 
Lesson 5 - Iteration

Iteration (also known as repetition or looping) constructs direct program flow to branch back and execute a block of code more than once. This way, the same block of code can be repeated many times thereby reusing existing code and automating certain procedures. Specifically, this lesson looks at the while, do-while, and for loops.

The while loop

While loops allow you to repeat a segment of code while a particular condition (normally a Boolean expression) is true. The general syntax for a while loop is shown below:

while (Boolean expression)
{
   // Loop statements go here
}

When the while statement is first executed, the condition is evaluated. If it’s true, the loop will be entered into and the statements in the body of the loop executed. Control then jumps back to the top of the loop and the condition is re-evaluated. While ever the condition remains true, the loop statements are executed over and over. When the condition becomes false, execution of the loop ends and control is passed to the first statement directly after the loop code.

It’s important to ensure that the statements in the body of the loop are able to change the condition in some way, otherwise the condition will remain true indefinitely and the loop will never end. This is referred to as an infinite loop and is undesirable.

Where while loops are generally used

While loops are generally used when you don't know the number of iterations required at design time (that is, when you're writing the program). In these situations, the number of loops required is based on some other variable in the program that is not known at design time.

While loops are often used in data validation. Data validation refers to the checking of input data to make sure it meets certain criteria. For example, consider a situation in which the user is prompted for a positive value. If the user enters a negative value, they should be given a warning and re-prompted for a new value. But what if the user re-enters an invalid value a second time, or even a third time? How can we predict how many times they'll enter an unacceptable value? The answer is to use a while loop that will continually prompt the user until valid data is entered. An example is shown below:

int value;
cout << "Please enter a positive value: ";
cin >> value;
while (value < 0)
{
   cout << "You cannot enter a negative value! Please re-enter: ";
   cin >> value;
}

In the above example, the user is prompted for a positive value. A while loop is then used to check if the value is not positive, that is, it's less than zero. If so, the body of the loop in entered. The user is given a warning message and a opportunity to re-enter a positive value. While ever the user enters a negative value, the while lop condition will be true and the user re-prompted. Only when the user enters a positive value will the loop condition become false and therefore end.

While loops can also be used when you do know how many iteration of the loop you want to do. When this is the case, a loop variable is normally initialised to zero and incremented each time through the loop until it reaches a certain value. Here's an example the prints the word Hello on the screen five times:

int counter = 0;
while (counter < 5)
{
   cout << "Hello" << endl;
   counter++;
}

In this example an integer variable counter is initialised to zero. The first time the loop condition is encountered it's evaluated to true because counters, having a value of 0, is less than 5. Therefore the body of the loop is executed. The word Hello is printed to the screen, than the variable counter is incremented to 1. This is still less than 5, and so the loop is executed again. This process continues for values of counter at 0, 1, 2, 3, and 4 (that is, five iterations). When counter reaches 5, it is no longer less than 5, so the loop ends.

The do-while loop

Do-while loops are very similar to while loops, except that they always execute at least once before the loop condition is checked. The general syntax for a while loop is shown below:

do
{
   // Loop statements go here

} while (Boolean expression);

When the do-while loop is first executed, control flows through the do statement and executes the body of the loop unconditionally. The while statement's condition at the end of the loop is then evaluated to check whether any further iterations of the loop are required (that is, if the condition is true). If so, the loop continues to execute while-ever the condition remains true. Do-while loops are often used when asking the user whether they want to use the program again or quit. A simple example is shown below:

char answer;
do
{
   // Program statements go here

   cout << "Would you like to play again (y/n)? ";
   cin >> answer;

} while (answer == 'y');

In this example, the workings of the program are placed inside a do-while loop. At the end of the program, the user is asked if they want to use the program again. If they answer 'y' for yes, the while condition becomes true and another iteration of the loop is made. This program assumes that any answer other than 'y' means no.

The for loop

For loops are used when you know how many iterations of the loop you want at design time. For loops normally contain three components: a loop initialisation statement, a condition for looping, and an expression that modifies the loop variable in some way (normally an increment or decrement statement). Consider the following example that displays the word Hello five times down the screen:

for (int i=0; i<5; i++)
{
   cout << "Hello" << endl;
}

In the above example, the statement int i=0 declares and initialises the loop variable i. It's customary to use the variable i in loops, however, any variable name can be used. The statement i<5 is the condition required to start the loop. The body of the loop will continue to be executed while ever i is less than 5. The final statement i++ increments the loop variable with each pass of the loop. Note that this statement is not terminated with a semicolon. In this example, the loop variable will count 0 to 4 before the loop ends.

For loops can also be made to count down. Consider the following example:

for (int count=10; count>0; count--)
{
   cout << count << " ";
}

In this example, the statement int count=10 declares and initialises the loop variable count. The statement count > 0 is the condition required for continued looping. The final statement count-- decrements the loop variable with each pass of the loop. In this example, the loop variable will count from 10 down to 1 before the loop ends. In this example, the loop variable count is displayed in the body of the loop followed by a space. The output of this code will be 10  9  8  7  6  5  4  3  2  1.

Problems with loops

Problems with loops include loops that never start, loops that never stop, and loops that do one more or one less iteration than expected. When designing loops, be sure to think the logic through very carefully.

Nested loops

The C++ compiler allows you to nest (embed) any type of control structure inside any other type of control structure. Therefore, it's possible to nest one loop inside another. An example is shown below that uses nested loops to display a 10 x 10 multiplication table:

for (int rows=1; rows<=10; rows++)
{
   for (int cols=1; cols<=10; cols++)
   {
      cout << rows * cols << "\t";
   }
   cout << endl;
}

The above example consists of an outer loop (responsible for counting through the rows of the table) and an inner loop (responsible for counting through the columns). For each iteration of the outer loop, the inner loop completes all its iterations. In other words, a total of 10 x 10 = 100 iterations of the inner loop are made. In the body of the inner loop we display the product of the two loop values, followed by the \t sequence which displays a Tab. When the inner loop is complete we start a new line by displaying an endl.

The break and continue keywords

The break and continue keywords can be used to modify the way loops behave. A break statement causes the loop to end unconditionally, while a continue statement causes the loop to ignore the rest of that iteration and go on to the next one.

Putting it all together - a guessing game

The program below is an implementation of a classic guessing game. The computer generates a random number between 1 and 100 but conceals it from the user. The user is then prompted to try to guess the number and computer responds by telling them whether their guess was "Too low", "Too high", or correct.
 

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include<ctime>

int main()
{
   int guess=0, secret;
   srand(time(0));
   secret = rand()%100+1;
   while (guess != secret)
   {
      cout << "Please enter your guess: ";
      cin >> guess;
      if (guess < secret)
         cout << "Too low" << endl;
      if (guess > secret)
         cout << "Too high" << endl;
   }
   cout << "Congratualations! You guessed correctly." << endl;
   return 0;
}
 

This program works as follows. Two variables are declared to store the user's guess and the secret number. The user's guess it initially set to a value of 0. The srand function is called to seed the random number generator, and rand is used to generate the secret number in the range 1 to 100. A while loop then checks that guess is not equal to secret. Initially this will be true because guess will be 0, and secret will be between 1 and 100. This forces the loop to start. In the body of the loop we check whether guess is greater or less than secret and display an appropriate message. If the two variables are equal, the loop will end, and a statement will be displayed congratulating the user.

 

Lesson 6 - Functions


 

 © 2006 learn2dostuff.com

Disclaimer