Lesson 5 - Conditions (branching) in the C++ language

Lesson highlights

Are you looking for a quick reference on conditions (branching) in C++ instead of a thorough-full lesson? Here it is:

Controlling the program's flow using the if keyword:

Click to edit
  • cout << "Enter your name:" << endl;
    string name;
    cin >> name;
    if (name == "Peter")
        cout << "Hey, I'm Peter too!" << endl; // printed only when Peter is entered
    cout << "Thanks for your name!" << endl; // printed always
    cin.get();
    
    • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.

    Reacting to both situations (when the condition is met and when not) using else and wrapping branches with multiple commands in {}:

    Click to edit
    • cout << "Enter your name:" << endl;
      string name;
      cin >> name;
      if (name == "Peter")
      {
          cout << "Hey, I'm Peter too!" << endl;  // printed only when Peter is entered
          cout << "Nice to meet you!" << endl;  // printed only when Peter is entered
      }
      else
          cout << "Nice to meet you, I'm Peter!" << endl; // printed for any other name
      cout << "Thanks for your name!" << endl; // printed always
      cin.get();
      
      • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.

      Using the && (the "and" operator) and || (the "or" operator) and eventually additional ()/if/else statements:

      Click to edit
      • cout << "Enter your name:" << endl;
        string name;
        cin >> name;
        if (name == "Peter")
        {
            cout << "Hey, I'm Peter too!" << endl; // printed only when Peter is entered
            cout << "Nice to meet you!" << endl; // printed only when Peter is entered
        }
        else {
            if (name == "Mike" || name == "Michael")
                cout << "My brother's name is Michael too!" << endl; // printed only when Michael is entered
            cout << "Nice to meet you, I'm Peter!" << endl; // printed for any other name than Peter
        }
        cout << "Thanks for your name!" << endl; // printed always
        cin.get();
        
        • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.

        Reacting to multiple states of one variable using a switch statement:

        Click to edit
        • cout << "Welcome to our calculator" << endl;
          cout << "Enter the first number:" << endl;
          double a;
          cin >> a;
          cout << "Enter the second number:" << endl;
          double b;
          cin >> b;
          cout << "Choose one of the following operations:" << endl;
          cout << "1 - addition" << endl;
          cout << "2 - subtraction" << endl;
          cout << "3 - multiplication" << endl;
          cout << "4 - division" << endl;
          int option;
          cin >> option;
          double result = 0.0;
          switch (option)
          {
              case 1:
                  result = a + b;
                  break;
              case 2:
                  result = a - b;
                  break;
              case 3:
                  result = a * b;
                  break;
              case 4:
                  result = a / b;
                  break;
          }
          if ((option > 0) && (option < 5))
              cout << "Result: " << result << endl;
          else
              cout << "Invalid option" << endl;
          cout << "Thank you for using our calculator. Press any key to end the program." << endl;
          cin.get(); cin.get();
          
          • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.

          Would you like to learn more? A complete lesson on this topic follows.

          In the previous lesson, More on the C++ type system: Data types, we discussed C++ data types in detail. We need to react somehow to different situations if we want to program something useful. It may be, for example, a value entered by the user, according to which we would like to change the running of the program. We metaphorically say that the program branches, and for branching we use conditions. We will pay attention to those in today's article. We're going create a program which calculates square roots, and we're going to improve our calculator.

          Conditions

          Conditions are written using the if keyword, which is followed by a logical expression. If the expression is true, the following statement will be executed. If it's not true, the following statement will be skipped, and the program will continue with the next statement. Let's try it out:

          Click to edit
          • if (15 > 5)
                cout << "True" << endl;
            cout << "The program continues here..." << endl;
            cin.get();
            
            • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.

            The output:

            Console application
            True
            The program continues here...

            If the condition is true, a command which writes a text to the console will be executed. In both cases the program continues. Of course, a variable can also be part of the expression:

            Click to edit
            • cout << "Enter a number" << endl;
              int a;
              cin >> a;
              if (a > 5)
                  cout << "The number you entered is greater than 5!" << endl;
              cout << "Thanks for the input!" << endl;
              cin.get();
              
              • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.

              Let's look at the relational operators which can be used in expressions:

              Meaning Operator
              Equal to ==
              Greater than >
              Less than <
              Greater than or equal to >=
              Less than or equal to <=
              Not equal !=
              Negation !

              We use the == operator for equality to avoid confusing it with a normal assignment to a variable, i.e. the = operator. If we wanted to negate an expression, we would write it in parentheses and write an exclamation mark before the actual expression within the parentheses. If you wanted to execute more than one command, you would have to insert commands into a block of curly brackets:

              Click to edit
              • #include <iostream>
                #include <cmath>
                using namespace std;
                
                int main()
                {
                    cout << "Enter a number and I'll calculate its square root:" << endl;
                    int a;
                    cin >> a;
                    if (a >= 0)
                    {
                        cout << "The number you entered is non-negative, so I can calculate it!" << endl;
                        double root = sqrt((double)a);
                        cout << "The square root of " << a << " is " << root << endl;
                    }
                    cout << "Thanks for the input" << endl;
                    cin.get(); cin.get();
                    return 0;
                }
                • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.


                Console application
                Enter a number and I'll calculate its square root:
                144
                You've entered a number greater than 0, I can calculate it!
                Square root of 144 is 12
                Thanks for the input

                The program retrieves a number from the user, and if it is non-negative, it calculates its square root. We have used the sqrt() math function before, which is declared with some other useful mathematical functions in the cmath file (don't forget to include it at the beginning of your code). sqrt() returns the value as a double. Since it can work with multiple data types, we have to specify which version we're going to use. Therefore, we cast the variable to double. There are multiple ways we can do so:

                1. type(value)
                2. (type)value
                3. (type)(value)

                It'd be nice if our program yelled at us if we entered a negative number. With our current knowledge, we could write something like this:

                Click to edit
                • #include <iostream>
                  #include <cmath>
                  using namespace std;
                  
                  int main()
                  {
                      cout << "Enter a number and I'll get its square root:" << endl;
                      int a;
                      cin >> a;
                      if (a >= 0)
                      {
                          cout << "The number you entered is non-negative, so I can calculate it!" << endl;
                          double root = sqrt((double)a);
                          cout << "The square root of " << a << " is " << root << endl;
                      }
                      if (a < 0)
                          cout << "I can't calculate the square root of a negative number!" << endl;
                      cout << "Thanks for the input" << endl;
                      cin.get(); cin.get();
                      return 0;
                  }
                  • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.

                  The code can be greatly simplified by using the else keyword which executes the following statement or block of statements if the condition was not true:

                  Click to edit
                  • #include <iostream>
                    #include <cmath>
                    using namespace std;
                    
                    int main()
                    {
                        cout << "Enter a number and I'll get its square root:" << endl;
                        int a;
                        cin >> a;
                        if (a >= 0)
                        {
                            cout << "The number you entered is non-negative, so I can calculate it!" << endl;
                            double root = sqrt((double)a);
                            cout << "The square root of " << a << " is " << root << endl;
                        }
                        else
                            cout << "I can't calculate the square root of a negative number!" << endl;
                        cout << "Thanks for the input" << endl;
                        cin.get(); cin.get();
                        return 0;
                    }
                    • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.

                    The code is much clearer, and we don't have to make up a negating condition which could be very difficult with complex conditions sometimes. In the case of multiple commands, we would have to use a {} block again after the else keyword.

                    Else is also used when we need to set a variable from the condition up so we can't evaluate it later on. The program remembers that the condition didn't apply and it'll move to the else branch. Let's look at an example: Consider a number whose value will be either 0 or 1 and we'll be asked to swap these values (if there is 0, we'd put a 1 there, and the other way around). Naively, we could write a code like this:

                    Click to edit
                    • int a = 0; // the variable is initialized with a value of 0
                      
                      if (a == 0) // if the value is 0, we change its value to 1
                          a = 1;
                      if (a == 1) // if the value is 1, we change its value to 0
                          a = 0;
                      
                      cout << a << endl;
                      cin.get();
                      
                      • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.

                      It doesn't work, does it? Let's take a closer look at the program. At the very beginning, a contains a value of 0, the first condition is undoubtedly fulfilled and it assigns a 1 into a. Well, suddenly, the second condition becomes true. What should we do then? If we swapped the conditions, we would have the same problem with 1. Now, how do we solve this? You guessed it, using else!

                      Click to edit
                      • int a = 0; // the variable is initialized with a value of 0
                        
                        if (a == 0) // if the value is 0, we change its value to 1
                            a = 1;
                        else // if the value is 1, we change its value to 0
                            a = 0;
                        
                        cout << a << endl;
                        cin.get();
                        
                        • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.

                        In C++, we could even replace the condition with a = !a; which would replace the 0 and 1 values in a variable.

                        Conditions can be made using two basic logical operators:

                        Operator Syntax
                        Logical AND &&
                        Logical OR ||

                        Let's take a look at the example:

                        Click to edit
                        • cout << "Enter a number between 10-20:" << endl;
                          int a;
                          cin >> a;
                          if ((a >= 10) && (a <= 20))
                              cout << "The condition has been met." << endl;
                          else
                              cout << "You did it wrong." << endl;
                          cin.get(); cin.get();
                          
                          • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.

                          Of course, operators can be combined with parentheses:

                          Click to edit
                          • cout << "Enter a number between 10-20 or 30-40:" << endl;
                            int a;
                            cin >> a;
                            if (((a >= 10) && (a <= 20)) || ((a >=30) && (a <= 40)))
                                cout << "The condition has been met." << endl;
                            else
                                cout << "You did it wrong." << endl;
                            cin.get(); cin.get();
                            
                            • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.

                            Switch

                            Switch is a construct taken from the C language, like most of C++'s syntax. It allows us to relatively simplify the usage of if-else command sequences. Let's think back to our calculator from the previous lesson, which had read two numbers and calculated all 4 operations. Now, we want to single out an operation. Without the switch, we would write the code out like this:

                            Click to edit
                            • cout << "Welcome to our calculator" << endl;
                              cout << "Enter the first number:" << endl;
                              double a;
                              cin >> a;
                              cout << "Enter the second number:" << endl;
                              double b;
                              cin >> b;
                              cout << "Choose one of the following operations:" << endl;
                              cout << "1 - addition" << endl;
                              cout << "2 - subtraction" << endl;
                              cout << "3 - multiplication" << endl;
                              cout << "4 - division" << endl;
                              int option;
                              cin >> option;
                              double result = 0.0;
                              if (option == 1)
                                  result = a + b;
                              else
                              if (option == 2)
                                  result = a - b;
                              else
                              if (option == 3)
                                  result = a * b;
                              else
                              if (option == 4)
                                  result = a / b;
                              if ((option > 0) && (option < 5))
                                  cout << "Result: " << result << endl;
                              else
                                  cout << "Invalid option" << endl;
                              cout << "Thank you for using our calculator. Press any key to end the program." << endl;
                              cin.get(); cin.get();
                              
                              • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.


                              Console application
                              Welcome to our calculator
                              Enter the first number:
                              3.14
                              Enter the second number:
                              2.72
                              Choose one of the following operations:
                              1 - addition
                              2 - subtraction
                              3 - multiplication
                              4 - division
                              2
                              result: 0.42
                              Thank you for using our calculator. Press any key to end the program.

                              Notice that we've declared the variable result at the beginning, so we could later assign something to it. If we declared it at every assignment, the program wouldn't compile. A variable can only be declared once. C++ is also not able to tell whether a value is actually assigned to the variable result. For this reason, we assign zero to variable result at the beginning. Another trick is validating the user's choice. The program should still work the same even without all the elses (but why keep on asking if we already have a result).

                              Now, here's the same program using a switch:

                              Click to edit
                              • cout << "Welcome to our calculator" << endl;
                                cout << "Enter the first number:" << endl;
                                double a;
                                cin >> a;
                                cout << "Enter the second number:" << endl;
                                double b;
                                cin >> b;
                                cout << "Choose one of the following operations:" << endl;
                                cout << "1 - addition" << endl;
                                cout << "2 - subtraction" << endl;
                                cout << "3 - multiplication" << endl;
                                cout << "4 - division" << endl;
                                int option;
                                cin >> option;
                                double result = 0.0;
                                switch (option)
                                {
                                    case 1:
                                        result = a + b;
                                        break;
                                    case 2:
                                        result = a - b;
                                        break;
                                    case 3:
                                        result = a * b;
                                        break;
                                    case 4:
                                        result = a / b;
                                        break;
                                }
                                if ((option > 0) && (option < 5))
                                    cout << "Result: " << result << endl;
                                else
                                    cout << "Invalid option" << endl;
                                cout << "Thank you for using our calculator. Press any key to end the program." << endl;
                                cin.get(); cin.get();
                                
                                • Keep your outputs the same, it's how the task should look like and the only way the tests will pass.

                                As you can see, the code is a bit clearer now. If we needed to execute multiple commands in any branch of the switch, surprisingly, we wouldn't write it into the {} block. Instead, we would write it just under the first command. The {} block is replaced by a break command that takes us out from the entire switch. Aside from case x:, switches can also contain the default: branch, which will be executed if none of the cases applied. It's up to you whether you use a switch or not. Generally, it's only useful when you have a larger amount of branches and you could always replace it with if-else sequences. Don't forget to add breaks.

                                That is all for today. In the next lesson, Solved tasks for C++ lessons 4-5, we'll take a look at arrays and loops, i.e. finish up with the absolute basics of the C++ language. Look forward to it :)

                                In the following exercise, Solved tasks for C++ lessons 4-5, we're gonna practice our knowledge from previous lessons.


                                 

                                Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

                                Download

                                By downloading the following file, you agree to the license terms

                                Downloaded 3x (290.23 kB)
                                Application includes source codes in language C++

                                 

                                Do you like this article?
                                Before saving the rating, please explain the author what's wrongCharacters 0 of 50-500
                                Previous article
                                More on the C++ type system: Data types
                                All articles in this section
                                C++ Basic Constructs
                                Skip article
                                (not recommended)
                                Solved tasks for C++ lessons 4-5
                                Article has been written for you by David Capka Hartinger
                                Avatar
                                User rating:
                                No one has rated this quite yet, be the first one!
                                The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
                                Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
                                Activities