cpp
Control Flow
06_Control_Flow⚙️cpp
/**
* ============================================================
* C++ CONTROL FLOW - CONDITIONAL STATEMENTS
* ============================================================
*
* This file covers:
* - if statements
* - if-else statements
* - else-if chains
* - switch statements
* - Ternary operator
*
* Compile: g++ -std=c++17 -Wall 01_conditionals.cpp -o conditionals
* Run: ./conditionals
*
* ============================================================
*/
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "============================================" << endl;
cout << " C++ CONDITIONAL STATEMENTS" << endl;
cout << "============================================" << endl << endl;
// ========================================================
// PART 1: if STATEMENT
// ========================================================
cout << "--- PART 1: if STATEMENT ---" << endl << endl;
int age = 20;
// Simple if
if (age >= 18) {
cout << "You are an adult." << endl;
}
// Single statement (braces optional but recommended)
if (age >= 18)
cout << "You can vote." << endl;
// Multiple conditions with &&
int score = 85;
if (score >= 60 && score <= 100) {
cout << "Valid passing score: " << score << endl;
}
// Multiple conditions with ||
char grade = 'A';
if (grade == 'A' || grade == 'B') {
cout << "Excellent performance!" << endl;
}
cout << endl;
// ========================================================
// PART 2: if-else STATEMENT
// ========================================================
cout << "--- PART 2: if-else STATEMENT ---" << endl << endl;
int number = 7;
if (number % 2 == 0) {
cout << number << " is even." << endl;
} else {
cout << number << " is odd." << endl;
}
// Check positive/negative
int value = -5;
if (value > 0) {
cout << value << " is positive." << endl;
} else if (value < 0) {
cout << value << " is negative." << endl;
} else {
cout << "Value is zero." << endl;
}
cout << endl;
// ========================================================
// PART 3: else-if CHAIN (Multiple Conditions)
// ========================================================
cout << "--- PART 3: else-if CHAIN ---" << endl << endl;
int marks = 75;
cout << "Marks: " << marks << endl;
cout << "Grade: ";
if (marks >= 90) {
cout << "A+ (Excellent)" << endl;
} else if (marks >= 80) {
cout << "A (Very Good)" << endl;
} else if (marks >= 70) {
cout << "B (Good)" << endl;
} else if (marks >= 60) {
cout << "C (Satisfactory)" << endl;
} else if (marks >= 50) {
cout << "D (Pass)" << endl;
} else {
cout << "F (Fail)" << endl;
}
// Day of week example
int day = 3;
string dayName;
if (day == 1) dayName = "Monday";
else if (day == 2) dayName = "Tuesday";
else if (day == 3) dayName = "Wednesday";
else if (day == 4) dayName = "Thursday";
else if (day == 5) dayName = "Friday";
else if (day == 6) dayName = "Saturday";
else if (day == 7) dayName = "Sunday";
else dayName = "Invalid";
cout << "Day " << day << " is " << dayName << endl;
cout << endl;
// ========================================================
// PART 4: NESTED if STATEMENTS
// ========================================================
cout << "--- PART 4: NESTED if STATEMENTS ---" << endl << endl;
int x = 10, y = 20, z = 15;
cout << "Finding largest of " << x << ", " << y << ", " << z << endl;
int largest;
if (x >= y) {
if (x >= z) {
largest = x;
} else {
largest = z;
}
} else {
if (y >= z) {
largest = y;
} else {
largest = z;
}
}
cout << "Largest: " << largest << endl;
// Login example
string username = "admin";
string password = "secret123";
bool isAdmin = true;
if (username == "admin") {
if (password == "secret123") {
if (isAdmin) {
cout << "Welcome, Administrator!" << endl;
} else {
cout << "Welcome, User!" << endl;
}
} else {
cout << "Incorrect password." << endl;
}
} else {
cout << "User not found." << endl;
}
cout << endl;
// ========================================================
// PART 5: switch STATEMENT
// ========================================================
cout << "--- PART 5: switch STATEMENT ---" << endl << endl;
int dayNum = 3;
cout << "Day " << dayNum << " is: ";
switch (dayNum) {
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;
}
// Fall-through behavior
cout << "\nGrade classification:" << endl;
char letterGrade = 'B';
switch (letterGrade) {
case 'A':
case 'B':
cout << "Excellent!" << endl;
break;
case 'C':
cout << "Good" << endl;
break;
case 'D':
cout << "Satisfactory" << endl;
break;
case 'F':
cout << "Failed" << endl;
break;
default:
cout << "Invalid grade" << endl;
}
// Calculator example
double num1 = 10, num2 = 5;
char op = '*';
double result;
cout << "\nSimple calculator: " << num1 << " " << op << " " << num2 << " = ";
switch (op) {
case '+':
result = num1 + num2;
cout << result << endl;
break;
case '-':
result = num1 - num2;
cout << result << endl;
break;
case '*':
result = num1 * num2;
cout << result << endl;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
cout << result << endl;
} else {
cout << "Error: Division by zero" << endl;
}
break;
default:
cout << "Invalid operator" << endl;
}
// C++17 init statement in switch
cout << "\nC++17 switch with init:" << endl;
switch (int val = 42; val % 10) {
case 0:
cout << val << " ends with 0" << endl;
break;
case 2:
cout << val << " ends with 2" << endl;
break;
default:
cout << val << " ends with something else" << endl;
}
cout << endl;
// ========================================================
// PART 6: TERNARY OPERATOR
// ========================================================
cout << "--- PART 6: TERNARY OPERATOR ---" << endl << endl;
int a = 10, b = 20;
// Ternary: condition ? value_if_true : value_if_false
int max = (a > b) ? a : b;
cout << "Max of " << a << " and " << b << " is " << max << endl;
// Ternary for string selection
int userAge = 15;
string category = (userAge >= 18) ? "Adult" : "Minor";
cout << "Age " << userAge << " is categorized as: " << category << endl;
// Nested ternary (use sparingly, can be hard to read)
int num = 0;
string sign = (num > 0) ? "positive" :
(num < 0) ? "negative" : "zero";
cout << num << " is " << sign << endl;
// Ternary in output
bool isLoggedIn = true;
cout << "Status: " << (isLoggedIn ? "Online" : "Offline") << endl;
// Ternary for absolute value
int negNum = -15;
int absVal = (negNum < 0) ? -negNum : negNum;
cout << "Absolute value of " << negNum << " is " << absVal << endl;
cout << endl;
// ========================================================
// PART 7: C++17 if WITH INITIALIZER
// ========================================================
cout << "--- PART 7: C++17 if WITH INITIALIZER ---" << endl << endl;
// if with initialization (C++17)
if (int squared = 5 * 5; squared > 20) {
cout << squared << " is greater than 20" << endl;
}
// Useful for checking function results
// if (auto result = someFunction(); result.isValid()) { ... }
cout << endl;
// ========================================================
// BEST PRACTICES
// ========================================================
cout << "============================================" << endl;
cout << "BEST PRACTICES:" << endl;
cout << "============================================" << endl;
cout << "1. Always use braces {} even for single statements" << endl;
cout << "2. Use switch for multiple discrete values" << endl;
cout << "3. Don't forget break in switch cases" << endl;
cout << "4. Use ternary for simple conditions only" << endl;
cout << "5. Avoid deeply nested conditions" << endl;
cout << "6. Consider early return to reduce nesting" << endl;
cout << "============================================" << endl;
return 0;
}
// ============================================================
// EXERCISES:
// ============================================================
/*
* 1. Write a program to check if a year is a leap year
* (divisible by 4, but not 100, unless also by 400)
*
* 2. Create a simple menu system using switch
*
* 3. Write a program that determines the type of triangle
* based on three side lengths
*
* 4. Create a grading system that takes marks and outputs
* the grade and performance description
*/