OnlineCBT Logo OnlineCBT
C++ · LESSON 5

Control Flow: Conditionals and Loops

By Ratan Updated: 15 Oct 2026

Implement decision logic and loops with range-based for loops (for (auto x : vec)).

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Select branches and traverse containers

C++ has if, else, switch, for, while and do-while. Use explicit braces and make boundary conditions testable. Range-based for loops simplify element traversal when you do not need an index.

Worked example: count passing marks

#include 
#include 
int main() {
    std::vector marks{35, 40, 82, 19};
    int passes{0};
    for (int mark : marks) {
        if (mark >= 40) {
            ++passes;
        }
    }
    std::cout << "Passes: " << passes << '\n';
    for (int& mark : marks) {
        if (mark < 100) ++mark;
    }
    std::cout << marks[0] << '\n';
}

Expected lines: Passes: 2 and 36. The first range loop copies each int into mark. The second uses a reference and changes the elements themselves. For larger read-only objects, const auto& avoids unnecessary copying.

Choose the loop for the requirement

A counted for loop exposes initialization, condition and update together. while fits input-driven repetition. do-while runs at least once, which can suit an interactive menu. break leaves the nearest loop or switch; continue starts the next loop iteration. Make sure a continue in a while loop cannot skip the only progress update.

Condition boundaries

Check invalid values before classifying them. For a score category, order thresholds from the highest to the lowest so broad conditions do not capture cases intended for narrower branches. With arrays or vectors, valid indices stop before size(); i <= size() goes one element too far.

Container mutation during traversal

Do not add elements to a vector inside a range-based loop over that same vector without understanding iterator invalidation. Reallocation can invalidate the loop's stored iterators. Collect new elements separately or use a deliberate algorithm with a clearly defined mutation rule.

Exercises

  1. Compute the sum of marks before the increment. Answer: 176.
  2. Count failures instead; expect 2.
  3. Change the second loop from int& to int. Why do stored marks remain unchanged? Only the local copies are incremented.
  4. Test thresholds at 39, 40 and 41 rather than only a comfortable value such as 82.

हिन्दी संकेत: range loop में value copy और reference का फर्क समझें। Bounds और iterator validity दोनों जरूरी हैं।

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat