else
The else
statement in C++ is used to provide an alternate block of code to be executed if the condition of an if
statement is false.
The general syntax of an else
statement is as follows:
if (condition) { // code to execute if the condition is true } else { // code to execute if the condition is false }
For example, the following code uses an else
statement to print a different message depending on whether the number variable is positive or negative:
#include <iostream> using namespace std; int main() { int x = 0; cin >> x; if (x > 0) cout << "This number is positive" << endl; else cout << "This number is negative" << endl; return 0; }
Output should be one of the previous statements depending on the entered number. if the number is positive like 5, the output will be “This number is positive” and vice versa.
The else
statement is a powerful tool for controlling the flow of your program. By using else
statements, you can write more complex and efficient code.
Here are some general rules for using the if else
statement:
- The
else
statement must be used in conjunction with anif
statement. - The
else
statement can be used to provide an alternate block of code to be executed if the condition of theif
statement is false. - You can use nested
if else
statements to create more complex conditional statements:#include <iostream> using namespace std; int main() { int x = 0; cin >> x; if (x % 2 == 0) if (x > 50) cout << "it's Ok" << endl; else cout << "it's not Ok" << endl; else cout << "Odd" << endl; return 0; }
By understanding how to use the if else
statement, you can write more efficient and reliable C++ code.