In this lesson, you will learn about the if..else.. if statement in C++, with examples to better understand the topic.
The if…else statement is used to decide between two options before executing a piece of code. However, we utilize the if…else if…else expression if we have to choose between more than two options.
Basic Syntax
if (condition1) { // statement(s) } else if (condition2) { // statement(s) } -- -- -- -- -- -- else if (conditionN) { // statement(s) } else { // statement(s) }
In the above syntax, the code block runs if condition 1 evaluates to true.
Example
//A program compares two numbers, whether the number1 is greater or less or equal to number2 #include <iostream> using namespace std; int main() { int Number1, Number2; cout << "Please enter the first number: "; cin >> Number1; cout << "Please enter the second number: "; cin >> Number2; if (Number1 > Number2) { cout << Number1 << " is greater than " << Number2; } else if (Number1 < Number2) { cout << Number1 << " is less than " << Number2; } else { cout << Number1 << " is equal to " << Number2; } return 0; }
Output
Please enter the first number: 6 Please enter the second number: 6 6 is equal to 6
We ask the user for two integers in this Program. After that, we determine whether the value is bigger, less, or equal to two by using the “if…else…if…else” ladder.
Alternately, you can substitute the ternary “operator?:” for the “if..else” expression. A simple way to express an “if…else” expression is with the ternary operator.
Example
//Program compares two numbers whether number1 is greater or less or equal to number2 #include <iostream> using namespace std; int main() { int Number1, Number2; cout << "Please enter first integer: "; cin >> Number1; cout << "Please enter second integer: "; cin >> Number2; (Number1 >= Number2) ? cout << Number1 << " is greater.": cout << Number1 << " is less."; return 0; }
Output
Please enter first integer: 12 Please enter second integer: 11 12 is greater.
This concludes the C++ if..else..if Statement lesson. The next lesson will teach you about the Switch Statement in C++.