Beginner7 min readLesson 14 of 50
The if Statement
Use if to run code only when a condition is true:
if (condition) {
// code runs when condition is true
}
#include <iostream>
using namespace std;
int main() {
int score = 85;
if (score >= 90) {
cout << "Grade: A" << endl;
}
if (score >= 80) {
cout << "Grade: B" << endl;
}
return 0;
}
Output:
Grade: B
else and else if
#include <iostream>
using namespace std;
int main() {
int score;
cout << "Enter score: "; cin >> score;
if (score >= 90) {
cout << "A — Excellent!" << endl;
} else if (score >= 80) {
cout << "B — Good" << endl;
} else if (score >= 70) {
cout << "C — Average" << endl;
} else if (score >= 60) {
cout << "D — Below Average" << endl;
} else {
cout << "F — Fail" << endl;
}
return 0;
}
Ternary Operator
A shortcut for simple if-else in one line:
// Syntax: condition ? valueIfTrue : valueIfFalse
int age = 20;
string status = (age >= 18) ? "Adult" : "Minor";
cout << status; // Adult
Note: The ternary operator is great for simple assignments but becomes hard to read when nested. Prefer if-else for complex conditions.
Exercise
Write a program that reads a temperature (in °C) and prints: "Hot" if > 30, "Warm" if 15–30, "Cold" if below 15.
Show Solution
#include <iostream>
using namespace std;
int main() {
int temp;
cout << "Enter temperature (C): "; cin >> temp;
if (temp > 30) {
cout << "Hot" << endl;
} else if (temp >= 15) {
cout << "Warm" << endl;
} else {
cout << "Cold" << endl;
}
return 0;
}
Quiz
What does the else block execute?
- A) Always
- B) When the
if condition is true - C) When the
if condition is false - D) Never
Answer
C) The else block runs when the preceding if condition evaluates to false.
What is the ternary operator syntax?
- A)
condition : true ? false - B)
condition ? true : false - C)
if(cond) ? val1 : val2 - D)
cond && val1 || val2
Answer
B) condition ? true : false
Summary
if executes a block when the condition is true.
else if adds additional conditions.
else runs when no conditions matched.
- The ternary operator
?: is a compact one-line if-else.