blog.dopana

Back

Third post in the basic C++ series. Programs mostly run top to bottom, but real programs need decisions and repetition.

If and else#

int score = 85;

if (score >= 90) {
    std::cout << "Grade: A\n";
} else if (score >= 70) {
    std::cout << "Grade: B\n";
} else {
    std::cout << "Grade: C\n";
}
cpp

The condition must be a boolean expression. Use && for AND, || for OR, and ! for NOT. Always brace the bodies — it prevents bugs when you add a line later.

Switch#

For many discrete values, switch is clearer than a chain of else if:

switch (day) {
    case 1:
        std::cout << "Monday\n";
        break;
    case 2:
        std::cout << "Tuesday\n";
        break;
    default:
        std::cout << "Weekend\n";
        break;
}
cpp

break stops fall-through. Forgetting it is a classic C++ bug.

While and do-while#

int n = 3;
while (n > 0) {
    std::cout << n << " ";
    --n;
}
// prints: 3 2 1
cpp

while checks before running. do-while runs at least once:

int n;
do {
    std::cout << "Enter a positive number: ";
    std::cin >> n;
} while (n <= 0);
cpp

For loops#

for bundles initialization, condition, and step:

for (int i = 0; i < 5; ++i) {
    std::cout << i << " ";
}
// prints: 0 1 2 3 4
cpp

Range-based for#

Iterating over a container is simplest with a range-based loop:

std::vector<int> v{10, 20, 30};
for (int x : v) {
    std::cout << x << " ";
}
cpp

break and continue#

  • break exits the loop immediately.
  • continue skips the rest of the current iteration and moves to the next.
for (int i = 0; i < 10; ++i) {
    if (i % 2 == 0) continue;   // skip even numbers
    if (i > 7) break;           // stop at 9
    std::cout << i << " ";
}
// prints: 1 3 5 7
cpp

Conclusion#

Conditionals choose a path; loops repeat work. Together they turn linear code into real logic. Next in this series: functions.

References#