Conditional statements in C++ are used to make decisions in a program. The if, else if, and else statements allow the program to execute different blocks of code based on conditions.
What are if, else if, else Statements?
These statements are used to control the flow of a program.
ifchecks a conditionelse ifchecks another condition if the previous one is falseelseruns when all conditions are false
They are commonly used in decision-making and logical operations.
Syntax of if Statement
if (condition) {
// code to execute
}
Example of if Statement
#include <iostream>
using namespace std;
int main() {
int age = 18;
if (age >= 18) {
cout << "You are eligible to vote.";
}
return 0;
}
Syntax of if else Statement
if (condition) {
// code if condition is true
}
else {
// code if condition is false
}
Example of if else Statement
#include <iostream>
using namespace std;
int main() {
int number = 5;
if (number % 2 == 0) {
cout << "Even Number";
}
else {
cout << "Odd Number";
}
return 0;
}
Syntax of if else if else Statement
if (condition1) {
// code
}
else if (condition2) {
// code
}
else {
// code
}
Example of if else if else
#include <iostream>
using namespace std;
int main() {
int marks = 75;
if (marks >= 80) {
cout << "Grade A";
}
else if (marks >= 60) {
cout << "Grade B";
}
else {
cout << "Grade C";
}
return 0;
}
How if, else if, else Work
- The
ifcondition is checked first - If true, its block executes
- If false, the
else ifcondition is checked - If all conditions are false, the
elseblock runs
Nested if Statement
You can also place an if statement inside another if statement.
#include <iostream>
using namespace std;
int main() {
int age = 20;
bool hasID = true;
if (age >= 18) {
if (hasID) {
cout << "Access Granted";
}
}
return 0;
}
Why if, else if, else are Important
These conditional statements are important because they:
- Help programs make decisions
- Control the program flow
- Handle different conditions efficiently
- Improve logical programming
- Are widely used in real-world applications
Real-Life Example
Think of a traffic signal:
- If light is green → Go
- Else if light is yellow → Slow down
- Else → Stop
This is how conditional statements work in programming.
Conclusion
The if, else if, and else statements in C++ are essential for decision-making in programs. They allow developers to create logical and interactive applications by executing different code blocks based on conditions.