else if
Estimated reading: 3 minutes
165 Views
The
else if
statement in C++ is a conditional statement that allows you to execute different blocks of code based on a series of conditions. The general syntax of an else if
statement is as follows:if (condition1) { // code to execute if condition1 is true } else if (condition2) { // code to execute if condition1 is false and condition2 is true } else if (condition3) { // code to execute if condition1 and condition2 are false and condition3 is true } ... else { // code to execute if none of the conditions are true }
The else if
statements are evaluated in order, and the first else if
statement whose condition evaluates to true
is executed. If none of the else if
conditions evaluate to true
, the else
statement is executed.
Here is an example of an else if
statement:
#include <iostream> using namespace std; int main() { int mark = 0; cin >> mark; if (mark >= 90) cout << "A" << endl; else if (mark >= 80) cout << "B" << endl; else if (mark >= 70) cout << "C" << endl; else if (mark >= 60) cout << "D" << endl; else cout << "F" << endl; return 0; }
Another example:
#include <iostream> using namespace std; int main() { int x = 0, y = 0; cout << "Enter 2 numbers" << endl; cin >> x >> y; if (x < y) cout << "y is greater than x" << endl; else if (x > y) cout << "x is greater than y" << endl; else cout << "Both are equal" << endl; cout << "C++ is great language!" << endl; return 0; }
You can also use nested else if
statements to create even more complex conditional statements.
The else if
statement is a powerful tool for controlling the flow of your program. By using else if
statements, you can write more complex and efficient code.
Here are some general rules for using the else if
statement:
- The
else if
statement must be used in conjunction with anif
statement. - The
else if
statements are evaluated in order, and the firstelse if
statement whose condition evaluates totrue
is executed. - If none of the
else if
conditions evaluate totrue
, theelse
statement is executed. - You can use nested
else if
statements to create even more complex conditional statements.
By understanding how to use the else if
statement, you can write more efficient and reliable C++ code.