If-Else Statements in C++ tutorial
If-Else Statements in C++ cplus
If-Else statements are fundamental decision-making constructs in C++ that allow your program to execute certain code blocks conditionally, based on whether an expression evaluates to true or false.
if (condition) {
// Code to execute if condition is true
}
Example:
#include <iostream>
using namespace std;
int main() {
int age = 20;
if (age >= 18) {
cout << "You are eligible to vote." << endl;
}
return 0;
}
Output:
You are eligible to vote.
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
#include <iostream>
using namespace std;
int main() {
int number = 5;
if (number % 2 == 0) {
cout << "Even number" << endl;
} else {
cout << "Odd number" << endl;
}
return 0;
}
Output:
Odd number
This is used when you want to test multiple conditions.
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if none of the above is true
}
Example:
#include <iostream>
using namespace std;
int main() {
int marks = 85;
if (marks >= 90) {
cout << "Grade A" << endl;
} else if (marks >= 75) {
cout << "Grade B" << endl;
} else {
cout << "Grade C" << endl;
}
return 0;
}
Output:
Grade B
Always use clear and simple conditions.
Avoid deeply nested if-else chains; use switch if suitable.
Use braces {} even for single statements to prevent logical errors.