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
.
Line | Description |
---|---|
5 | Creates two variables of type integer with the names firstNumber and secondNumber |
7 | Prompts the user to enter the first number |
8 | The entered number is stored to variable firstNumber |
9 | Prompts the user to enter the second number |
10 | The entered number is stored to variable secondNumber |
12 – 13 | If 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 – 15 | If firstNumber is smaller than secondNumber , the string “value_first_variable < value_second_variable” is output |
16 – 17 | Otherwise the string “value_first_variable = value_second_variable” is output |
#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;
}
Please enter first number: 6
Please enter second number: 7
6 < 7