Decisions, Decisions!

Choice

Any computer language needs a way of testing things and making decisions based on the result of the state of the program. To do this, C++ uses an if statement. The structure of the if statement looks like this:

if (condition)
   {
      do these statements if the condition passes
   }
else
   {
      do these statements if the condition fails
   }

The if statement tests a condition (more on this below), which can either be true or false. If the condition is true, then the program does one instruction (or set of instructions). If it is false, then it does another set.

Conditions

Here is an example of a short program with a condition in it:

// Your first conditional program?
#include <iostream.h>
void main ()
    { int x;
      cout << "Please type a whole number from 1 to 10 : ";
      cin >> x;
      if (x == 5)
        cout << "You typed my favourite number!" << endl;
      cout << "Thank you and goodbye!" << endl;
    }

This program asks you to type a whole number from 1 to 10. You do so, and it then tests it to see if it is equal to 5 (the (x == 5) part), and if it is, it prints out the message about 5 being its favourite number (Ahh!)

The (x == 5) is called the condition. You can see that it is either true or false, depending on what you typed for the number. The brackets are essential - C++ complains if you don't put them in.

Note that you don't need to put ; after the (x == 5). This is because (x == 5) is not the end of the statement. That only happens when the instruction after the conditon has been carried out. The cout instruction definitely does need ; after it.

Warning! Note also the double equal sign == in the condition. This is necessary in a condition to see if two things are equal to each other. We used a single equals sign in variable assignment, but C++ treats testing and assignment as different:

a = 2*my_age
Setting the value of a
(a == 2*my_age)
Testing the value of a

If you want to see what a difference an extra equals sign makes, try replacing (x == 5) with (x = 5). Whatever number you type now, the condition always passes. The reason is that (x = 5) is making x equal to 5. The condition then returns the number 5, which C++ interprets as TRUE, so whatever you type, the condition is always true. This is an especially insidious bug which catches out even experienced programmers like me.

== isn't the only test you can do. Here are some others:

< Less than This returns true if the expression on the left is less than the expression on the right, so a+b < 2*first_try returns true if a+b is less than 2*first_try.
> Greater than This returns true if the expression on the left is bigger than the expression on the right, so 6.1*(a+b) > 2*first_try returns true if 6.1*(a+b) is greater than 2*first_try.
<= Less than or equal to This returns true if the expression on the left is less than or the same as the expression on the right, so a+b <= 2*first_try returns true if a+b works out at less than 2*first_try or if they both produce the same number. If a+b comes to greater than 2*first_try, then it produces false.
>= Greater than or equal to This returns true if the expression on the left evaluates to more than or the same as the expression on the right, so 30 >= x*y returns true if 30 works out at greater than x*y or if they both produce the same number. If 30 comes to less than x*y, then it produces false.
!= Not equal to This returns true if the expression on the left comes to something different from the expression on the right, so a+b != 2*first_try returns true if a+b works out at a different value to 2*first_try. If a+b comes to the same as 2*first_try, then it produces false.

Here is the program from up above with a few modifications to check that you really have typed a number from 1 to 10 :

// A better version of the above
#include <iostream.h>
void main ()
    { int x;
      cout << "Please type a whole number from 1 to 10 : ";
      cin >> x;
      if (x > 10)
        cout << "That number is too big!" << endl;
      if (x < 1)
        cout << "That number is too small!" << endl;
      if (x != 5)
        cout << "You didn't get the right number!" << endl;
      cout << "Thank you and goodbye!" << endl;
    }

A Worked Example

Here is a more sophisticated version of the calculator program you saw in a previous section.

// Calculator
#include <iostream.h>
void main ()
    { float first_num, second_num; // The two numbers
      int which_one;          // Specified calculation
      float result;            // The answer.
      cout << "Please enter the first number : ";
      cin >> first_num;
      cout << "Please enter the second number : ";
      cin >> second_num;

      cout << "Press 1 to add the two numbers"
           << endl
           << "Press 2 to subtract the two numbers."
           << endl
           << "Press 3 to multiply the two numbers."
           << endl
           << "Press 4 to divide the two numbers."
           << endl;

      cin >> which_one;
      if (which_one == 1)
        result = first_num + second_num;
      if (which_one == 2)
        result = first_num - second_num;
      if (which_one == 3)
        result = first_num * second_num;
      if (which_one == 4)
        result = first_num / second_num;
      cout << "The result is " << result << endl;
    }

I'll leave you to work out how the program operates.

Blocks of Statements

An if statement often needs to control several statements at once. You group statements together into blocks using the { and } symbols. This example shows an if statement that prints out several lines of text:

if (x == 5)
  { cout << "Well done!" << endl;
    cout << "You guessed my number." << endl;
    cout << "What's your favourite number?" << endl;
  }

Here you have several statements, each ending with ; and surrounded by { and }. If the condition passes, all three statements are carried out. If the condition fails, none of them is carried out.

The else statement

If you compare the if statements that we have been using to the one that I gave you at the top of this section you will notice a bit missing - the else part.

The else part of the statement is optional - we haven't needed it up to now. It includes one or more statements (blocked together using { and } in the case of more than one) that are carried out if the condition fails.

cout << "Please type the number 8 : ";
cin >> x;
if (x == 8)
  cout << "Thank you! I appreciate that." << endl;
else
  { cout << "No, blockhead!" << endl;
    cout << "Why can't you follow simple instructions?"
         << endl;
  }

Here there is only one statement in the main part of the if statement, so it doesn't need to have { and } round it. The else part contains two statements, so it definitely does need { and }.

There is a ; after the first cout statement. It looks a little odd coming before the else part, but it is just following a statement, so you should be used to it by now.

Warning! if statements are done in an identical way in JavaScript to what you have learned above. If you are not easily confused by the slight differences between C++ and JavaScript, you should consider reading the corresponding section of the JavaScript tutorial.


Go back
Top of the page
Main Menu
Questions
Worked Examples
Go on
Go back
Top of the page
Main Menu
Questions
Worked Examples
Go on