C++ If-Else Statement
The if-else statement in C++ allows you to execute one block of code if a condition is true and another block if the condition is false. It is an extension of the basic if statement for handling two possible outcomes.
Syntax
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example Program
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
// If-Else statement
if (number % 2 == 0) {
cout << "The number is even." << endl;
} else {
cout << "The number is odd." << endl;
}
return 0;
}
Output (example)
Enter a number: 7 The number is odd.
Key Points
- The
elseblock executes only if theifcondition is false. - You can have multiple
if-else if-elsechains to check multiple conditions. - Braces
{ }are optional for single statements but recommended for clarity.
Next Topic
After if-else statements, you can learn about Nested If Statements to handle multiple layers of conditions.