C++ Code Example: multi-branches

In C++ there are also multiple branches represented by the else if statement

The if-conditions are evaluated in sequence until one of them is true. Then finally the code section belonging to this condition is executed and the multiple branching handling is finished. The else-part is only executed if none of the conditions is true.

Code Explanation

LineDescription
5Creates two variables of type integer with the names firstNumber and secondNumber
7Prompts the user to enter the first number
8The entered number is stored to variable firstNumber
9Prompts the user to enter the second number
10The entered number is stored to variable secondNumber
12 – 13If the value of the variable firstNumber is greater than the value of the variable secondNumber, the string “value_first_variable > value_second_variable” is output
14 – 15If firstNumber is smaller than secondNumber, the string “value_first_variable < value_second_variable” is output
16 – 17Otherwise the string “value_first_variable = value_second_variable” is output
#include &lt;iostream&gt;
using namespace std;

int main() {
    int firstNumber, secondNumber;

    cout << "Please enter first number: ";
    cin >> firstNumber;
    cout << "Please enter second number: ";
    cin >> secondNumber;

    if (firstNumber > secondNumber) {
        cout << firstNumber << " > " << secondNumber;
    } else if (firstNumber < secondNumber) {
        cout << firstNumber << " < " << secondNumber;
    } else {
        cout << firstNumber << " = " << secondNumber;
    }

    return 0;
}
Output
Please enter first number: 6
Please enter second number: 7
6 < 7