2. C++ Control Flow, Range-Based Loops & Conditionals

Comprehensive Guide: Operators, if-else, switch case, while, do-while & C++11 range-based for loops

Module 1: Control Flow: Conditionals & Switch Case

Making logical decisions using Boolean branch evaluations.

🇬🇧 English Definition

Control Flow statements evaluate boolean expressions to select which code blocks execute during program execution.

🇮🇳 Hinglish Definition

Control flow se program ki execution direction decide hoti hai (if, else if, switch).

Core Concepts & Rules

  • Ternary Operator: string status = (score >= 50) ? 'Pass' : 'Fail';
  • switch case handles integral and character choices cleanly.

🔍 Line-by-Line Code Breakdown

  1. Line 2: Set int score = 85.
  2. Line 3-7: if-else statement checks if score >= 80 to print distinction status.
💻 Practical C++ Code Example - Control Flow: Conditionals & Switch Case
using namespace std;

int main() {
    int score = 85;
    if (score >= 80) {
        cout << "Grade: Distinction by Instructor Student!" << endl;
    } else {
        cout << "Grade: Standard Pass" << endl;
    }
    return 0;
}
📤 Compiled C++ Output:
Grade: Distinction by Instructor Student!

Module 2: C++11 Range-Based for Loop

Simplifying array and container iteration using modern syntax.

🇬🇧 English Definition

A range-based for loop iterates through all elements in an array or container sequentially without requiring manual indexing.

🇮🇳 Hinglish Definition

Range-based for loop se array ya vector ke saare items ko bina index manage kiye direct process kiya ja sakta hai.

Core Concepts & Rules

  • Syntax: for (dataType element : container) { ... }
  • Use auto &element to iterate elements by reference to avoid copying.

🔍 Line-by-Line Code Breakdown

  1. Line 2: Initialize int numbers[] = {10, 20, 30, 40}.
  2. Line 3-5: Range-based for loop: for (int num : numbers) printing each element.
💻 Practical C++ Code Example - C++11 Range-Based for Loop
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40};
    cout << "Array Elements: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    return 0;
}
📤 Compiled C++ Output:
Array Elements: 10 20 30 40