LearnForFree
C++ For Beginners
Lesson

Conditional Statements (if, else if, else, switch, Ternary)

By default, a C++ program executes statements sequentially from top to bottom. Conditional statements allow your program to make decisions and execute different blocks of code based on whether a condition evaluates to true or false. 1. if, else if, and else • if: Executes its block {} only if the condition inside parentheses () is true. • else if: Tests a new condition if the previous if (or else if) was false. You can chain as many else if blocks as needed. • else: Acts as a fallback catch-all that runs if none of the preceding conditions were true. 2. The switch Statement When comparing a single integer or character variable against many exact constant values, a switch statement is cleaner than a long if-else if chain. • Each case checks for an exact match. • break: Crucial keyword at the end of each case. Without break, execution "falls through" into the next case below it. • default: Optional fallback case if no case matches. 3. The Ternary Operator (? :) A compact, one-line shorthand for simple if-else assignments: condition ? value_if_true : value_if_false;
#include <iostream> #include <string> int main() { int score = 85; // 1. if - else if - else if (score >= 90) { std::cout << "Grade: A\n"; } else if (score >= 80) { std::cout << "Grade: B\n"; } else { std::cout << "Grade: C or below\n"; } // 2. Ternary Operator std::string status = (score >= 60) ? "Passed" : "Failed"; std::cout << "Status: " << status << "\n"; // 3. switch Statement char menuOption = '2'; switch (menuOption) { case '1': std::cout << "Starting New Game...\n"; break; case '2': std::cout << "Loading Saved Game...\n"; break; default: std::cout << "Invalid Option\n"; break; } return 0; }

Watch companion video on YouTube

Sign in to save your progress