C++ If Else Statements

In our previous tutorial, we learned about C++ input and output to make our programs more interactive. Well, today we are going to learn how to use If Then Else statements to allow us to control the flow of the program. This will allow us to execute code based on a given condition. Below is a simple example.

Example of Control Flow

Boolean Comparison Operators

Before we teach you how to write these statements, we’ll show you the boolean comparison operators you may use for creating conditions. These condition statements will return either TRUE or FALSE which are useful in if statements.

Operator Example Description
> a > b, a > 2, 4 > 2 Greater than
>= a >=b, a >= 2, 4 >= 2 Greater than or equal to
< a < b, a < 2, 4 < 2 Less than
<= a <= b, a <=2, 4 <= 2 Less than or equal to
== a == b, 2 == a Equal to
!= a != b, 2 != a Does Not Equal to

You may use these boolean operators to compare data types of similar type. You may compare any of the C++ Data Types with each others whether they are literals such as 2, 3, “Hello”, or variables. If you compare mixed data types you will get different behavior.

Below are some examples of conditions. If they are literals, determine the conditions truth value.

2 < number
 
"Hello" == "HELLO"
 
'a' != 'A'
 
2.0 == 2

You may also use the && (and) and || (or) connectives in order to have multiple conditions. Below is an everyday example and after that some C++ examples.

Examples for both && and ||

 
// Returns true if both the 1st and 2nd conditions are true
2 < a && b > c
 
// Returns true if either the 1st or 2nd conditions are true
2 < a || b > c

Finally, you may also use the ! connective to make a condition have the opposite truth value. An example is below:

int a, b;
a = 2;
b = 3;
 
// The following would return TRUE
a < b 
 
// The following would return FALSE because the ! 
// negates the truth value between the parenthesis
! ( a < b )

C++ If Statement

We will now start by showing you the syntax for writing an if statement.

if ( condition ) { 

statements ...

}

Now, we’ll actually put it to some use. In our previous tutorial we learned about user input which will help us make things a lot more interesting. Let’s say we wanted to create a program that asks the user to guess a number and we’ll simply reply if it was the correct one. We’d do it in the following manner.

1
2
3
4
5
6
7
8
9
10
11
int magicNumber = 27;
 
int guess;
 
cout << "Guess my magic number: ";
 
cin >> guess;
 
if ( magicNumber == guess ) {
     cout << "Congratulations! Correct guess!" << endl;
}

In the code above, the statement inside the if clause would execute if the condition were true. Therefore, if the user chooses our magic number 27, our program will congratulate the user.

If Statement Diagram

C++ If Else Statement

Well, what if they didn’t? We would want to give them another message saying it was incorrect. Your first guess might be making another if statement but we can use the else statement.

if ( condition ) { 

statements ...

} else { 

statements ...

}
1
2
3
4
5
6
7
// .. Previous code
 
if ( magicNumber == guess ) {
     cout << "Congratulations! Correct guess!" << endl;
} else { 
    cout << "Incorrect!" << endl;
}

In the previous code, if the user guess the number correctly, the program would congratulate the user. If the user did not guess the number correctly, it would display Incorrect!

If Else Statement

C++ If Else If Else Statement

Now, what if we wanted to actually let them know if their guess was too high or too low if it was incorrect? We can then use the else if statements.

if ( condition ) { 

statements ...

} else if ( condition ) { 

statements ...

} else { 

statements ...

}
1
2
3
4
5
6
7
8
9
// .. Previous code
 
if ( magicNumber == guess ) {
     cout << "Congratulations! Correct guess!" << endl;
} else if ( magicNumber > guess ) {
    cout << "Your guess is too low!" << endl;
} else {
    cout << "Your guess is too high!" << endl;
}

If Else Else If Statements

Nesting If Statements

You may also have nest if statements within if statements. An example is below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
cin >> guess;
number = 25;
 
if ( number == guess ) {
 
     cout << "Now try guessing the second number!\n";
     // Guess a second number
     number = 56;
     cin >> guess;
 
     if ( number == guess ) { 
         cout << "Congratulations! You guess two numbers correctly!\n";
     } else { 
         cout << "Try next time!\n";
     }
} else { 
    cout << "Incorrect!\n";
}

Overview of If Statements

Some things to know about if statements are mentioned below.

  1. Remember, the else statement is optional and you may have zero, one, or more else if statements.
  2. For good practice always indent or more formally known as tab your code when its within an if statement. That way it’s easy to follow. Imagine going over nested if statements that don’t have tabs? You would have a hard time figuring out which statements belong where.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    if ( a > b ) { 
    if ( c < 2 ) {
    cout << "Yes!";
    } 
    else { 
    cout << "No!";
    }
    } 
    else { 
    cout << "What?";
    }
  3. If you only have one statement within an if statement you may omit the {}’s. For good practice, just keep them. It’s easier for someone else to go back to read and add to your code.
    1
    2
    3
    4
    5
    6
    7
    8
    
    if ( a == b ) { 
        cout << "Yes!";
    } 
     
    // Is the same as
     
    if ( a == b ) 
        cout << "Yes!";

Going further with If Statement

Now that you know the basics of If Statements, why not do the following?

  1. Create an if statement that contains a condition that is always true.
  2. Are “Hello” and “HELLO” equivalent? What about the char ‘a’ and a string “a”?
  3. Create a 3rd level deep if statement. The previous example shown was nested 2x.

Keep patient, in our next tutorial we will learn about for loops and then while loops. Once we get a good handle of control flow, we can make some interesting programs.

Tags: , , , , , ,