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
elsestatement must be used in conjunction with anifstatement. - The
elsestatement can be used to provide an alternate block of code to be executed if the condition of theifstatement is false. - You can use nested
if elsestatements 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.