Chapter 9 – If...Else Statement

9.1  Basic If Statement

The if statement is used to test a condition and offer a branch in the program depending on the result of the test.  The next program shows how to use a basic if statement.  This program asks the user to enter a number.  If the number they enter is greater than 5, then the program outputs, "Your number is greater than 5."  Otherwise, the program will not output anything.

Program 9.1 - Basic If Statement

#include <iostream>
using namespace std;

int main()
{
  int A;
  cout << "Enter an integer: ";
  cin >> A;
  if (A > 5)
    cout << "Your number is greater than 5.\n";
}

Output
Enter an integer: 9
Your number is greater than 5.

In preceding program, immediately following the if statement is the condition (A > 5).  A condition either evaluates to true or false.  If the condition is true, then the line following the condition is executed.  If the condition is false, the program will skip this line.  Notice there is no semicolon after the if statement.  The if statement technically ends after the cout statement.

9.2  If...Else Statement

Immediately following an if statement, we can add an else statement as shown in the next program.  For the output, we run the program twice.  In the first output, we assume the user enters a 9 at the cin statement.  In the second output, we assume the user enters a 3.

 

Program 9.2a - If...Else Statement

#include <iostream>
using namespace std;
int main()
{
  int A;
  cout << "Enter an integer: ";
  cin >> A;
  if (A > 5)
    cout << "Your number is greater than 5.\n";
  else
    cout << "Your number is less than or equal to 5.\n";
}

Output 1
Enter an integer: 9
Your number is greater than 5.

Output 2
Enter an integer: 3
Your number is less than or equal to 5.

With an if...else statement, only one of the two cout statements will execute - not both.  The next program shows how to use the "is equal to" comparison.

Program 9.2b – Equal To Comparison

#include <iostream>
using namespace std;
int main()
{
  int Number, Option, Total;
  cout << "Enter an integer: ";
  cin >> Number;

  cout << "Choose an option, 1 = square number, 2 = cube number : ";
  cin >> Option;

  if (Option == 1)
    Total = Number * Number;

  else

    Total = Number * Number * Number;

  cout << "The answer is " << Total << endl;

}

Output
Enter an integer: 3

Choose an option, 1 = square number, 2 = cube number : 2
The answer is 27

In the previous program, we assume the user entered 3 for the integer, and chose option 2 to cube the number.  Therefore, the else statement executes since the variable Option is not equal to 1.
 

9.3  Comparison Operators

The following table shows all the comparison operators that can be used with an if statement. 

Comparison Operators

Operator

Description

Less than

Greater than

<=

Less than or equal to

>=

Greater than or equal to

==

Equal to

!=

Not equal to

 

Important:  It is a common mistake to forget to use two equal signs == when testing for equality.  If you accidentally use only one equal sign, it will not cause a syntax error, but your program will probably not work the way you were hoping.  Using a single equal sign in a condition is an assignment statement.  As shown below, you will assign a value to the variable.  If the value you are assigning is 0, then the condition evaluates to false.  Otherwise, it evaluates to true.

if (Option = 5)      // This assigns 5 to Option and evaluates to true

if (Option = 0)      // This assigns 0 to Option and evaluates to false

Again, always remember to use two equal signs  == in you condition when testing for equality.

if (Option == 5)     // The proper condition tests to see of Option equals 5

 

The program below uses all of the comparison operators.  In this program, we assume the user enters 75 for the value of A.  The only condition that does not evaluate to true is: if (A <= 40).

Program 9.3 – All Comparison Operators

#include <iostream>

using namespace std;

int main()
{
  int A;
  cout << "Enter a value for A: ";
  cin >> A;
  if (A > 5)
    cout << "A is greater than 5.\n";
  if (A < 100)
    cout << "A is less than 100.\n";
  if (A >= 50)
    cout << "A is greater than or equal to 50.\n";
  if (A <= 40)
    cout << "A is less than or equal to 40.\n";
  if (A == 75)
    cout << "A is equal to 75.\n";
  if (A != 20)
    cout << "A is not equal to 20.\n";
}

Output
Enter a value for A: 75
A is greater than 5.
A is less than 100.
A is greater than or equal to 50.
A is equal to 75.
A is not equal to 20.

 

9.4  Using Braces with the If Statement

In the preceding programs, we only have one cout statement to execute after each if statement.  If you have multiple statements to execute on the condition of an if or an else, then you will need to use braces after these statements.  Many programmers will always use braces for clarity.  The next program shows how to use an if statement to ask the user what they want the program to do.

Program 9.4 – If...Else Statement with Braces

#include <iostream>

using namespace std;
int main()
{
  int Choice;
  cout << "Select one of the following:\n";
  cout << " (1) Calculate the area of a circle.\n";
  cout << " (2) Calculate the area of a triangle.\n";
  cout << "Your choice: ";
  cin >> Choice;
  if (Choice == 1)
  {
    float R;
    cout << "Enter a radius: ";
    cin >> Radius;
    cout << "The area is " << 3.14 * R * R << endl;
  }
  else
  {
    float Base, Height;
    cout << "Enter the base: ";
    cin >> Base;
    cout << "Enter the height: ";
    cin >> Height;
    cout << "The area is " << 0.5 * Base * Height << endl; 
  }
}

Output
Select one of the following:
(1) Calculate the area of a circle.
(2) Calculate the area of a triangle.
Your choice: 1
Enter a radius: 2
The area is 12.56

 

In the previous program, notice that after each opening brace, the lines following are indented.  Indentation after braces shows the different levels in your program – similar to indentation in a table of contents.  Indentation will not change the way your program executes – it is intended to make the source code more readable.  You may choose how many spaces to indent, or to insert a tab.  Some editors like in Visual C++ will indent your program automatically when you insert braces.

 

9.5  Logical Operators: AND, OR, and NOT

When you have multiple conditions that all must be true, then you will need to use the logical AND (&&) operator within the condition.  The next program demonstrates this.

Program 9.5a – Logical AND Operator

#include <iostream>

using namespace std;
int main()
{
  int A;
  cout << "Enter a value for A: ";
  cin >> A;
  if (A >= 1 && A <= 10)
    cout << "A is between 1 and 10\n";
  else
    cout << "A is not between 1 and 10\n";
}

Output
Enter a value for A: 7

A is between 1 and 10

 

In the previous program, both conditions must be true to execute the first cout statement –

(A >=1) and (A <=10).  If one or both of the conditions are false, then the second cout statement will execute.  Notice that each of the conditions is evaluated before the logical AND operator.  Although it is not necessary, you can use addition parentheses in your condition as shown below.

 

if ((A >= 1) && (A <= 10))

 

When testing multiple conditions in which only one needs to be true, then you will need to use the logical OR (||) operator.  This is typed using two vertical bars, or pipe symbols – above Enter on your keyboard.  With a logical OR, at least one of the conditions must be true for the condition to evaluate to true.  The next program demonstrates the logical OR.

 

Program 9.5b – Logical OR Operator

#include <iostream>

using namespace std;
int main()
{
  int A;
  cout << "Enter a number between 1 and 10: ";
  cin >> A;
  if (A == 2 || A == 4 || A == 6 || A == 8 || A == 10)
    cout << "Your number is even.\n";
  else
    cout << "Your number is odd.\n";
}

Output
Enter a number between 1 and 10: 7

Your number is odd.

 

A third operator is the logical NOT (!).  This will negate any condition it is placed in front of – i.e. the condition will evaluate to the opposite value.  The example below demonstrates this.

 

if (!(A == 1))     // Evaluates to false if A is equal 1, and true otherwise

 

The words true and false may be used in a condition.  This might be useful if you are testing a program and need a condition to always evaluate to true or false – you can temporarily substitute the condition with the word true or false.  The following cout statement will always execute:

 

if (true)

  cout << "This will always print";

9.6  Ternary Conditional Operator

 

The conditonal or ternary operator allows you to put an if...else statement in an assignment statement.  The statement below uses this conditional operator to convert the variable Number to its absolute value.
 

  Condition   Value if
  conditon true
  Value if
  condition false
Number = (Number > 0) ? Number : -1 * Number;

 

After the equal sign on the above assignment statement is a condition (Number > 0).  If the condition is true, then the expression after the question mark (Number) will be assigned to Number.  If the condition is false, then the expression after the colon (-1 * Number) will be assigned to Number.

The next program demonstrates use of the ternary conditional operator.

 

Program 9.6 – Ternary Conditional Operator

#include <iostream>
using namespace std;
int main()
{
  char Choice;

  int Donuts;

  cout << "Please select an option\n";
  cout << "1 = eat a dozen donuts\n";

  cout << "2 = eat a half dozen donuts\n";
  cout << "Your choice: ";

  cin >> Choice;
  Donuts = (Choice == '1') ? 12 : 6;

  cout << "Have fun eating " << Donuts << " donuts.\n";

}

Output
Please select an option

1 = eat a dozen donuts

2 = eat a half dozen donuts

Your choice: 1

Have fun eating 12 donuts.

 


 

Exercises – Chapter 9

 

What will each of the conditions evaluate to – true or false?  Assume the following:  X = 5, Y = 8, Z = 20

1.  (X == 8)

2.  (Z != 20)

3.  (X == 3 || Z < 50)

4.  (Z == 20 && Y < 10)

5.  (!(Y >=6 && Y <=10))

6.  ((X != 5 || Y != 8) && Z == 20))

7.  ((X > 1 && Y > 10) || (Z <= 19 && Z >= 21))

8.  (X <= 5 && !(Z > 25))

9.  (!(Y > -5) || !(Z > -5))

10. (Z = 15 && Y = 10)

 

What will each of the following output?

 

11.    int A = 1;

       if (A > 0)

          cout << "Yes";

       else

          cout << "No";

 

 

12.    float B = 1.0, C = 2.0;

       if (C <= B)

          cout << "Apple";

       else

          cout << "Pear";

 

 

13.    bool X = false, Y = true, Z = true;

       if (Y && (X || Z))

          cout << "Yes";

       else

          cout << "No";

 

 

14.    int I = 4, J = -2, K = 0;

       if (!(J < I) && !(K >= J))

          cout << "red";

       else

          cout << "blue";

 

 

15. Write a program that prompts the user to enter an integer.  Let the user know whether their number is evenly divisible by 2, 3, and 4.