Department of Engineering

IT Services

6. Control Statements

department imageThe statements in the programs presented above have all been sequential, executed in the order they appear in the main program.

In many programs the values of variables need to be tested, and depending on the result, different statements need to be executed. This facility can be used to select among alternative courses of action. It can also be used to build loops for the repetition of basic actions.

Boolean expressions and relational operators

In C++ the testing of conditions is done with the use of Boolean expressions which yield bool values that are either true or false. The simplest and most common way to construct such an expression is to use the so-called relational operators.

x==y true if x is equal to y
x!=y true if x is not equal to y
x>y true if x is greater than y
x>=y true if x is greater than or equal to y
x<y true if x is less then y
x<=y true if x is less than or equal to y

Be careful to avoid mixed-type comparisons. If x is a floating point number and y is an integer the equality tests may not work as expected.

Compound boolean expressions using logical operators

If you need to test more than one relational expression at a time, it is possible to combine the relational expressions using the logical operators.

operator C++ symbol Example
AND && or and expression1 && expression2
OR || or or expression1 or expression2
NOT ! !expression

The meaning of these will be illustrated in examples below.

The IF selection control statement

The simplest and most common selection structure is the if statement which is written in a statement of the form:

if( boolean-expression ) statement;

The if statement tests for a particular condition (expressed as a boolean expression) and only executes the following statement(s) if the condition is true. An example follows of a fragment of a program which tests if the denominator is not zero before attempting to calculate fraction.

   if(total != 0)
      fraction = counter/total;

If the value of total is 0, the boolean expression above is false and the statement assigning the value of fraction is ignored.

If a sequence of statements is to be executed, this can be done by making a compound statement or block by enclosing the group of statements in braces.

   if( boolean-expression )
   {
        statements;
   }

An example of this is:

   if(total != 0)
   {
      fraction = counter/total;
      cout << "Proportion = " << fraction <<  endl;
   }
  

The IF/ELSE selection control statement

Often it is desirable for a program to take one branch if the condition is true and another if it is false. This can be done by using an if/else selection statement:

   if( boolean-expression )
        statement-1;
   else
        statement-2;

Again, if a sequence of statements is to be executed, this is done by making a compound statement by using braces to enclose the sequence:

   if( boolean-expression )
   {
        statements;
   }
   else
   {
        statements;
   }

An example occurs in the following fragment of a program to calculate the roots of a quadratic equation.

   // testing for real solutions to a quadratic
   d = b*b - 4*a*c;
   if(d >= 0.0) 
   {        
      // real solutions
      root1 = (-b + sqrt(d)) / (2.0*a);
      root2 = (-b - sqrt(d)) / (2.0*a);
      real_roots = true;
   }
   else
   {
      // complex solutions
      real = -b / (2.0*a);
      imaginary = sqrt(-d) / (2.0*a);
      real_roots = false;
   }

If the boolean condition is true, i.e. (d≥0), the program calculates the roots of the quadratic as two real numbers. If the boolean condition tests false, then a different sequence of statements is executed to calculate the real and imaginary parts of the complex roots. Note that the variable real_roots is of type bool. It is assigned the value true in one of the branches and false in the other.

ELSE IF multiple selection statement

Occasionally a decision has to be made on the value of a variable which has more than two possibilites. This can be done by placing if statements within other if-else constructions. This is commonly known as nesting and a different style of indentation is used to make the multiple-selection functionality much clearer. This is given below:

   if( boolean-expression-1 )
        statement-1;
   else if( boolean-expression-2 )
        statement-2;
   
   else
        statement-N;

For compound statement blocks, braces must be used.

SWITCH selection control statement

Instead of using multiple if/else statements C++ also provides a special control structure, switch.

For a variable x the switch(x) statement tests whether x is equal to the constant values x1, x2, x3, etc. and takes appropriate action. The default option is the action to be taken if the variable does not have any of the values listed.

   switch( x )
   {
      case x1:                                    
          statements1;
          break;
 
      case x2:
          statements2;
          break;

      case x3:
          statements3;
          break;

      default:
          statements4;
          break;
   }

The break statement causes the program to proceed to the first statement after the switch structure. Note that the switch control structure is different to the others in that braces are not required around multiple statements.

The following example uses the switch statement to produce a simple calculator which branches depending on the value of the operator being typed in. The operator is read and stored as a character value (char). The values of char variables are specified by enclosing them between single quotes. The program is terminated (return -1) if two numbers are not input or the simple arithmetic operator is not legal. The return value of -1 instead of 0 signals that an error took place.

(A copy of all the programs listed in this document can be found in the 1AC++Examples folder in your directory. You should compile and run these programs to help get a better understanding of how they work. Change directory and double click on the icon with the file name CalculatorSwitch.cc. Compile and run the program.)

// CalculatorSwitch.cc
// Simple arithmetic calculator using switch() selection.

#include <iostream>

using namespace std;

int main()
{
   float a, b, result;
   char operation;
 
   // Get numbers and mathematical operator from user input
   cin >> a >> operation >> b;

   // Character constants are enclosed in single quotes
   switch(operation)
   {
   case '+':
         result = a + b;
         break;

   case '-':
         result = a - b;
         break;

   case '*':
         result = a * b;
         break;

   case '/':
         result = a / b;
         break;

   default:
         cout << "Invalid operation. Program terminated." << endl;
         return -1;
   }

   // Output result
   cout << result << endl;
   return 0;
}

The WHILE repetition control statement

Repetition control statements allow the programmer to specify actions which are to be repeated while some condition is true. In the while repetition control structure:


   while( boolean-expression )
   {                             
       statements;
   }

the boolean expression (condition) is tested and the statements (or statement) enclosed by the braces are (is) executed repeatedly while the condition given by the boolean expression is true. The loop terminates as soon as the boolean expression is evaluated and tests false. Execution will then continue on the first line after the closing brace.

Note that if the boolean expression is initially false the statements (or statement) are not executed. In the following example the boolean condition becomes false when the first negative number is input at the keyboard. The sum is then printed. (Double click on the icon with the file name AddWhilePositive.cc and compile and run the program.

 // AddWhilePositive.cc
 // Computes the sum of numbers input at the keyboard.
 // The input is terminated when input number is negative.
  
#include <iostream>
  using namespace std;
  
int main()
  {
     float number, total=0.0;
     
   cout << "Input numbers to be added: " << endl;
     cin >> number;
  
   // Stay in loop while input number is positive
     while(number >= 0.0)
     {
         total = total + number;
         cin >> number;
     }
  
   // Output sum of numbers
     cout << total << endl;
     return 0;
  }
  

Increment and decrement operators

Increasing and decreasing the value of an integer variable is a commonly used method for counting the number of times a loop is executed. C++ provides a special operator ++ to increase the value of a variable by 1. The following are equivalent ways of incrementing a counter variable by 1.

   count = count + 1;
   count++;

The operator -- decreases the value of a variable by 1. The following are both decrementing the counter variable by 1.

   count = count - 1;
   count--;

The FOR repetition control statement

Often in programs we know how many times we will need to repeat a loop. A while loop could be used for this purpose by setting up a starting condition; checking that a condition is true and then incrementing or decrementing a counter within the body of the loop. For example we can adapt the while loop in AddWhilePositive.cc so that it executes the loop N times and hence sums the N numbers typed in at the keyboard.

   int i=0;          // initialise counter
   while(i<N)    // test whether counter is still less than N
   {
      cin >> number; 
      total = total + number;
      i++;       // increment counter
   }

The initialisation, test and increment operations of the while loop are so common when executing loops a fixed number of times that C++ provides a concise representation - the for repetition control statement:

   for(int i=0; i<N; i++)     
   {
      cin >> number; 
      total = total + number;
   }

This control structure has exactly the same effect as the while loop listed above.

The following is a simple example of a for loop with an increment statement using the increment operator to calculate the sample mean and variance of N numbers. The for loop is executed N times.
(Double click on the icon with the file name ForStatistics.cc and compile and run the program. Change the value of N (both negative and positive numbers) to make sure you understand the operation of both while and for loops.)

//ForStatistics.cc
//Computes the sample mean and variance of N numbers input at the keyboard.
//N is specified by the user but must be 10 or fewer in this example.

#include <iostream>
using namespace std;

int main()
{
   int    N=0;
   float  number, sum=0.0, sumSquares=0.0;
   float  mean, variance;

   // Wait until the user inputs a number in correct range (1-10)
   // Stay in loop if input is outside range
   while(N<1 || N>10)
   {
      cout << "Number of entries (1-10) = ";
      cin  >>   N;
   }

   // Execute loop N times
   // Start with i=1 and increment on completion of loop. 
   // Exit loop when i = N+1;
   for(int i=1; i<=N; i++ )
   {
       cout << "Input item number " << i << " = ";
       cin >> number;
       sum = sum + number;
       sumSquares = sumSquares + number*number;
   }

   mean = sum/N;
   variance = sumSquares/N - mean*mean;
   
   cout << "The mean of the data is " << mean << 
          " and the variance is " << variance << endl;
   return 0;
}

A more general form of the for repetition control statement is given by:

   for( statement1; boolean-expression; statement3 )     
   {
       statement2;
   }

The first statement (statement1) is executed and then the boolean expression (condition) is tested. If it is true statement2 (which may be more than one statement) and statement3 are executed. The boolean expression (condition) is then tested again and if true, statement2 and statement3 are repeatedly executed until the condition given by the boolean expression becomes false.

Try our C++ "for" loop teaching aid if you want some practise.

Back to top