Here are detailed examples of if, if-else, and if-else-if statements in C++ with explanations and outputs.
1️⃣ If Statement in C++
The if
statement executes a block of code only if a condition is true
.
🔹 Syntax
if (condition) {
// Code to execute if condition is true
}
✅ Example
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (num > 0) {
cout << "The number is positive." << endl;
}
cout << "End of program." << endl;
return 0;
}
🔹 Output (if input is 5)
Enter a number: 5
The number is positive.
End of program.
🔹 Output (if input is -3)
Enter a number: -3
End of program.
🚀 Explanation:
- The condition
num > 0
is checked. - If
true
, the message"The number is positive."
is printed. - If
false
, the program moves on without printing anything.
2️⃣ If-Else Statement in C++
The if-else
statement runs one block of code if the condition is true
, and another block if it is false
.
🔹 Syntax
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
✅ Example
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (num % 2 == 0) {
cout << "The number is even." << endl;
} else {
cout << "The number is odd." << endl;
}
return 0;
}
🔹 Output (if input is 4)
Enter a number: 4
The number is even.
🔹 Output (if input is 7)
Enter a number: 7
The number is odd.
🚀 Explanation:
- The condition
num % 2 == 0
checks if the number is even. - If
true
,"The number is even."
is printed. - If
false
,"The number is odd."
is printed.
3️⃣ If-Else-If Statement in C++
The if-else-if ladder allows checking multiple conditions.
🔹 Syntax
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if none of the above conditions are true
}
✅ Example
#include <iostream>
using namespace std;
int main() {
int marks;
cout << "Enter your marks: ";
cin >> marks;
if (marks >= 90) {
cout << "Grade: A" << endl;
} else if (marks >= 75) {
cout << "Grade: B" << endl;
} else if (marks >= 50) {
cout << "Grade: C" << endl;
} else {
cout << "Grade: F (Fail)" << endl;
}
return 0;
}
🔹 Output (if input is 88)
Enter your marks: 88
Grade: B
🔹 Output (if input is 40)
Enter your marks: 40
Grade: F (Fail)
🚀 Explanation:
- If
marks >= 90
, it prints"Grade: A"
. - Else, if
marks >= 75
, it prints"Grade: B"
. - Else, if
marks >= 50
, it prints"Grade: C"
. - Otherwise, it prints
"Grade: F"
.
📌 Summary
✔ if
Statement → Executes a block only if a condition is true.
✔ if-else
Statement → Runs one block if true, another if false.
✔ if-else-if
Ladder → Checks multiple conditions in sequence.
Would you like more examples on nested if statements or switch statements? 🚀
0 Comments