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 Example

This code prompts the user to enter two numbers, reads them from the console using cin, and stores them in integer variables firstNumber and secondNumber. It then compares the values of the two variables using a series of if, else if, and else statements, and prints a message to the console indicating whether the first number is greater than, less than, or equal to the second number.

If the value of firstNumber is greater than secondNumber, the program prints the message “firstNumber > secondNumber”. If firstNumber is less than secondNumber, the program prints the message “firstNumber < secondNumber”. If firstNumber is equal to secondNumber, the program prints the message “firstNumber = secondNumber”.

#include <iostream>
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