http://cpp.gantep.edu.tr
C++ resources. Faculty of Engineering, University of Gaziantep
 MAIN  -  Tutorials  -  Howtos  -  nmPrimer  -  Misc  -  Links  -  Contacts
C++ Tutorial (Basic)
[index][<][1][2][3][4][5][6][7][8][9][>]

3. Control structures: selection

Last modified: Sun, 04 Oct 2009 22:40:57 +0300

Complete: ##################-- (90%)

3.1 Introduction
3.2 Relational and Logical Operators
3.3 The if and if ... else Statements
3.4 The switch Statement
3.5 The ? Operator
3.6 Examples
3.7 Exercises

3.1 Introduction

The programs written in the previous sections have sequential execution; each staement in the program executes once, in order that they are listed. Control statements allow us to make decisions - the program takes one course of action or another depending on the value of a variable. This allows us to generate more flexible and useful programs.

This section describes the conditional statements: if, if ... else and switch, and also shows operators related to control structures.

3.2 Relational and Logical Operators

Control statements use relation operators in order to compare two objects. There are six relational operators as follows:

Relational Operators
Operator Description Example
< less than x < y
<= less than or equal to x <= y
> greater than x > y
>= greater than or equal to x >= y
== equal to x == y
!= not equal to x != y

Compound relation expressions can be formed using the Logical Operators

Logical Operators
Operator Description Example
&& logical AND, conjuction.
Both sides must be true for the result to be true
x > 2 && y == 3
|| Logical OR, disjunction.
The result is true if either side or both sides are true.
x > 2 || x <= 9
! Logical NOT, negation !(x>0)

Using these operators, we can form a Boolean Expression that can be either true or false. Boolean expressions evaluate to integer values. The value 0 means 'false' and all non-zero value means 'true'. There are also two literal constants used with bool variables: true and false.

Consider the following program section containing boolean expressions:

  int x=1, y=2, s;
  bool u, z, t, w;

  s = 2 > 1;
  u = x > 3;
  z = x <= y && y > 0;
  t = y <= 0 || z == true;
  w = !s;

  cout << " s=" << s << " u=" << u 
       << " z=" << z << " t=" << t << " w=" << w;
will output:
s=1   u=0   z=1   t=1
  • s = 1 (true) since 2 is always greater than 1
  • u = 0 (false) since x = 1 < 3
  • z = 1 (true) since x <= y and y > 0. Here both sides are true
  • t = 1 (true) since z is true. Here first side is false but second side is true
  • w = 0 (false) since s is true, therefore its negation is !s is false

3.3 The if and if ... else Statements

The if statement allows conditional execution. Its general form is:
  if (condition) {
    statements
    .
    .
  }
where condition is an integer expression and statements are any executable statement. These statements will be executed only if condition is true (nonzero). Note that, the use of braces ({}) is optional when statements consist of a single line.

As an example, the following code

  // this is a block if
  if (x == y) {
    cout << "x and y equal" << endl;
  }
is equivalent to
  // this is simple if
  if (x == y)
    cout << "x and y equal" << endl;
The simple if looks for only one condition. To execute an alternative condition we need to use the if ... else statement whose general for is:
  if (condition) {
    statements1
    .
    .
  }
  else {
    statements2
    .
    .
  }
Program 3.1 makes a test for divisibility of an integer number by another.

03prg01.cpp: Testing for divisibility
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
// Testing for divisibility
#include <iostream>
using namespace std;

int main()
{
  int number, d;

  cout << "Enter two integers: ";
  cin >> number >> d;

  if ( number%d == 0 )
    cout << number << " is divisible by " << d << endl;
  else
    cout << number << " is NOT divisible by " << d << endl;

  return 0;
}
Enter two integers: 24 6
24 is divisible by 6

---

Enter two integers: 32 5
32 is NOT divisible by 5

This program reads two integers and then checks the value of the remainder number%d. In the first run, value of 24%6 is 0, which means 24 is divisible by 6. However, in the second run, since 32%5 == 2, the condition is false and the else clause executes.

You will see an error message such as 'divide by zero' when d = 0. A compound condition can overcome this trouble, by replacing the if statement with the following:

  if(d !=0 && number%d == 0)
Another example of using the if statement is demonstrated in Program 3.2, which evaluates the roots of a quadratic equation ax2 + bx + c = 0. Here the real coefficients a, b and c are inputs to the program. Basically, the real roots can be calculated from .

03prg02.cpp: Finding roots of a quadratic equation
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
 19:
 20:
 21:
 22:
 23:
 24:
 25:
 26:
// Finding roots of a quadratic equation
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
  double a, b, c;

  cout << "Input the coefficients: ";
  cin >> a >> b >> c;

  double delta = b*b - 4.0*a*c;

  if(delta >= 0.0){
    double x1 = 0.5*(-b + sqrt(delta))/a;
    double x2 = 0.5*(-b - sqrt(delta))/a;
    cout << "There are two real roots: "
         << x1 << "  "<< x2 << endl;
  }
  else
    cout << "No real root exists. " << endl;

  return 0;
}
Input the coefficients: 1 1 1
No real root exists.

---

Input the coefficients: 2 0 -4
There are two real roots: 1.41421  -1.41421

If the number of conditions are greater than two in a program, then we can use else if statement. For example, the following compound function
can be implemented as
  if(x <= 0) 
    f = -x;
  else if (x>0 && x<1)
    f = x*x;
  else
    f = 1.0;

 Note that
Because an expression always has a value, one can take advantage of this feature in an if statement. A statement such as
if (x)       // if x is true (nonzero)
    x = 0;
can be read as "If x has a nonzero value, set it to 0". Actually, this is equivalent to
if (x != 0)  // if x is nonzero
    x = 0;

3.4 The switch Statement

The objective of this statement is to check several possible constant values for an expression. This is actually an alternative of the else if statement. It has the general form:
  switch (expression)
  {
    case constant1:
       group of statements 1;
       break;
    case constant2:
       group of statements 2;
       break;
    .
    .
    .
    default:
       default group of statements;
  }
switch evaluates expression and compares the result to each of the case values. If one of the case values matches the expression, execution jumps to those statements and continues to the end of the switch block, unless a break statement is encountered. (Here, break causes the immediate end of a switch. We will see the break statement in the next section again). If nothing matches, execution branches to the optional default statement.

As an example,

  switch(classCode){
     case 1:
        cout << "Freshman\n";
        break;
     case 2:
        cout << "Sophmore\n";
        break;
     case 3:
        cout << "Junior\n";
        break;
     case 4:
        cout << "Graduate\n";
        break;
     default:
        cout << "Illegal class code " << classCode << endl;
  }
This is equivalent to:
  if(classCode==1)
        cout << "Freshman\n";
  else if(classCode==2)
        cout << "Sophmore\n";
  else if(classCode==3)
        cout << "Junior\n";
  else if(classCode==4)
        cout << "Graduate\n";
  else
        cout << "Illegal class code " << classCode << endl;

Program 3.3 illustrates another use of the switch statement. The program reads two numbers and an operator, and then applies one of the four basic operations to the numbers. Three sample runs are given in the screen output column.

03prg03.cpp: Testing for divisibility
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
 19:
 20:
 21:
 22:
 23:
// Four basic operations with switch
#include <iostream>
using namespace std;

int main()
{
  char op;
  float x, y;

  cout << "Input first number : "; cin >> x;
  cout << "Input an operator  : "; cin >> op;
  cout << "Input second number: "; cin >> y;

  switch( op ){
    case '+': cout << "sum = " << x + y << endl; break;
    case '-': cout << "difference = " << x - y << endl; break;
    case '*': cout << "multiplication = " << x * y << endl; break;
    case '/': cout << "ratio = " << x / y << endl; break;
    default : cout << "undefined operator: " << op << endl;
  }

  return 0;
}
Input first number : 3
Input an operator  : +
Input second number: 5
sum = 8

---

Input first number : 3
Input an operator  : /
Input second number: 8
ratio = 0.375

---

Input first number : 10
Input an operator  : !
Input second number: 6
undefined operator: !

3.5 The ? Operator

C++ provides a short form of if ... else statement. It is called the conditional expression operator and has the general form:
  condition ? expression1 : expression2;
The value produced by this operation is either expression1 or expression2, depending on the condition. For example, the assignment statement,
  max =  (x > y) ? x : y;
will assign the value of x to max if x > y, otherwise it assigns the value of y to max. This is actually shorthand of
  if( x > y )  max = x;
  else         max = y;

Note that, this operator is useful when the condition and both expressions are very simply.

3.6 Examples

The following program outputs the ratio of two doubles that are input from the keyboard. The calculation yeilds a value that is always positive and a fraction.

03prg04.cpp: The positive fractional ratio of two numbers.
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
// The positive fractional ratio of two numbers
#include <iostream>
#include <cmath>
using namespace std;

int main () {
  double a, b;
  cout << "Input two numbers: ";
  cin >> a >> b;
  a=fabs(a); b=fabs(b);
  double ratio =  (a<b) ? a/b : b/a;
  cout << "The ratio is " << ratio << endl;
}
Input two numbers: -5.6 1.8
The ratio is 0.321429

3.7 Exercises

  1. What is the difference between x = 3 and x == 3?
  2. Are negative numbers true or false?
  3. What does the "conditional expression operator" do?
  4. What does if(x) and if(!x) mean?

  5. Rewrite the following line by using the if ... else statement.
    y = (x > 2 && x<=9) ? x*x:1.0/x;

  6. What is wrong with the following code?
    if( x > y > z ) cout << x*y*z << endl;

  7. What is the output of the following program?
    #include <iostream>
    int main(){
      int z, x = 11, y = 221;
    
      if(y) z = y < x ? x/y : y/x;
      else  z = 0.0;
    
      std::cout << "z = " << z << std::endl;
    
      return 0;
    }
    

  8. What is the output of the following program?
    #include <iostream>
    int main(){
      int a = 1, b = 1, c;
    
      if (c = (a-b)) std::cout << "The value of c is: " << c;
      else           std::cout << "The value of c is: " << c;
    
      return 0;
    }
    

  9. What is the output of the following program?
    #include <iostream>
    int main(){
      int a = 5, b = 7, c;
    
      if ( (c = a + b) != 35 )
        std::cout << "The value of c is: " << c;
      else
        std::cout << "The value of c is: " << c;
    
      return 0;
    }
    

  10. Write a program to input an integer number and output whether it is even or not.
  11. Write a program that reads a year from the keyboard and outputs whether it is leap year or not.
  12. Write a program that reads a grade A, B, C, D, or F and then prints "excellent", "good", "fair", "poor", or "failure". Use else if.
  13. Write a program for the previous exercise using switch statement.
[index][<][1][2][3][4][5][6][7][8][9][>]
please send us you comments/questions/corrections