Decision Making in C++
Decision making is one of the most important aspects of programming. C++ provides several mechanisms to control program flow based on specific conditions: if, if-else, else if, nested if, and switch. Choosing the right structure makes the code more efficient and easier to understand.
The if statement evaluates a boolean condition and executes a block of code if the condition is true. The switch statement is better suited for comparing one value against many possible constant values at once. A good understanding of both mechanisms is essential for writing correct programs.
Decision-Making Structures
1. If Statement
if (condition) {
// Code that runs if the condition is true
}
2. If-Else Statement
if (condition) {
// Code if the condition is true
} else {
// Code if the condition is false
}
3. Else If (Multi-branch)
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if all conditions are false
}
4. Nested If
if (condition1) {
if (condition2) {
// Code if both conditions are true
} else {
// Code if condition1 is true and condition2 is false
}
} else {
// Code if condition1 is false
}
5. Switch Statement
switch (expression) {
case value1:
// Code
break;
case value2:
// Code
break;
default:
// Default code
break;
}
Code Example
#include <iostream>
using namespace std;
int main() {
// If statement
cout << "=== If Statement ===" << endl;
int temperature = 38;
if (temperature > 37) {
cout << "Temperature " << temperature << "°C - Fever!" << endl;
}
// If-else
cout << "\n=== If-Else ===" << endl;
int age = 15;
if (age >= 18) {
cout << "Age " << age << " - Adult" << endl;
} else {
cout << "Age " << age << " - Child" << endl;
}
// Else if
cout << "\n=== Else If (Grade) ===" << endl;
int score = 78;
char grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
cout << "Score " << score << " = Grade " << grade << endl;
// Nested if
cout << "\n=== Nested If ===" << endl;
bool login = true;
int role = 2; // 1=admin, 2=user
if (login) {
if (role == 1) {
cout << "Welcome, Admin!" << endl;
} else if (role == 2) {
cout << "Welcome, User!" << endl;
} else {
cout << "Unknown role." << endl;
}
} else {
cout << "Please log in first." << endl;
}
// Switch statement
cout << "\n=== Switch Statement ===" << endl;
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day!" << endl;
break;
}
// Switch with fall-through
cout << "\n=== Switch with Fall-Through ===" << endl;
int month = 2;
int daysInMonth;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
daysInMonth = 31;
break;
case 4: case 6: case 9: case 11:
daysInMonth = 30;
break;
case 2:
daysInMonth = 28;
break;
default:
daysInMonth = 0;
}
if (month >= 1 && month <= 12) {
cout << "Month " << month << " has " << daysInMonth << " days" << endl;
} else {
cout << "Invalid month!" << endl;
}
return 0;
}
Code Explanation
- If Statement: Evaluates the condition and executes the block of code only if the condition is
true. If it isfalse, the block is skipped. - If-Else: Provides alternative code that runs when the condition is
false. It guarantees that some action is always taken. - Else If: Allows multiple branching for more than two possible conditions. It is evaluated from top to bottom and stops at the first
truecondition. - Nested If: An if inside an if. Useful for tiered conditions, but the code can become hard to read if it goes too deep.
- Switch: Compares one expression value against several constant values (cases). Each case ends with
breakto prevent fall-through. - Fall-through: If there is no
breakat the end of a case, execution "falls" into the next case. This can be used to combine several cases.
Switch vs If-Else Comparison
| Aspect | Switch | If-Else |
|---|---|---|
| Condition | One expression with many cases | Many different conditions |
| Data type | Integer, char, enum | Any boolean |
| Performance | Faster for many cases | Efficient for a few conditions |
| Flexibility | Equality check only | Supports ranges, complex expressions |
| Readability | Neater for many branches | More flexible |
Everyday Use Cases
Grading System:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int score;
cout << "=== Student Grading System ===" << endl;
cout << "Student name: ";
getline(cin, name);
cout << "Exam score: ";
cin >> score;
// Validate the input
if (score < 0 || score > 100) {
cout << "Error: Score must be between 0-100!" << endl;
return 1;
}
// Determine the grade and status
string grade, status;
if (score >= 85) {
grade = "A";
status = "Excellent";
} else if (score >= 75) {
grade = "B";
status = "Good";
} else if (score >= 65) {
grade = "C";
status = "Sufficient";
} else if (score >= 50) {
grade = "D";
status = "Poor";
} else {
grade = "E";
status = "Very Poor";
}
cout << "\nStudent: " << name << endl;
cout << "Score : " << score << endl;
cout << "Grade : " << grade << endl;
cout << "Status : " << status << endl;
// Check passing status with switch
bool passed = (score >= 50);
switch (passed) {
case true:
cout << "Decision: PASSED" << endl;
break;
case false:
cout << "Decision: FAILED" << endl;
cout << "Please retake it next semester." << endl;
break;
}
return 0;
}
Selection Menu:
#include <iostream>
using namespace std;
int main() {
int choice;
double num1, num2;
do {
cout << "\n=== Calculator Menu ===" << endl;
cout << "1. Addition" << endl;
cout << "2. Subtraction" << endl;
cout << "3. Multiplication" << endl;
cout << "4. Division" << endl;
cout << "5. Modulus" << endl;
cout << "0. Exit" << endl;
cout << "Choice: ";
cin >> choice;
if (choice == 0) {
cout << "Thank you!" << endl;
break;
}
if (choice < 1 || choice > 5) {
cout << "Invalid choice!" << endl;
continue;
}
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
switch (choice) {
case 1:
cout << "Result: " << num1 << " + " << num2 << " = " << (num1 + num2) << endl;
break;
case 2:
cout << "Result: " << num1 << " - " << num2 << " = " << (num1 - num2) << endl;
break;
case 3:
cout << "Result: " << num1 << " * " << num2 << " = " << (num1 * num2) << endl;
break;
case 4:
if (num2 != 0) {
cout << "Result: " << num1 << " / " << num2 << " = " << (num1 / num2) << endl;
} else {
cout << "Error: Division by zero!" << endl;
}
break;
case 5:
if (num2 != 0) {
cout << "Result: " << (int)num1 << " % " << (int)num2 << " = " << ((int)num1 % (int)num2) << endl;
} else {
cout << "Error: Modulus by zero!" << endl;
}
break;
}
} while (choice != 0);
return 0;
}
Conclusion
Decision making in C++ uses if-else for flexible conditions and switch for comparing many constant values. if-else supports ranges and complex conditions, while switch is neater and more efficient for many branches. Use else if for multiple branching and nested if for tiered conditions. Always watch out for fall-through in switch and make sure every case ends with break.