C/C++ Basics

Conditions, Loops, and switch

Combine branches and loops in a small classification program.

What is Conditions, Loops, and switch?

if chooses by a boolean condition, switch handles discrete cases, and loops repeat a block with explicit termination.

Important points

  • Compile with warnings enabled and fix every warning.
  • Know the lifetime and type of every value.
  • Validate input and keep array bounds explicit.

See how it works

Move the slider to change the score. The flowchart lights up the path the program takes, and the matching line of code is highlighted.

C and C++ code examples

C
Run code →
main.c
#include <stdio.h>

int main(void) {
    int scores[] = {92, 71, 84};
    int total = 0;
    for (int i = 0; i < 3; ++i) total += scores[i];
    int average = total / 3;
    switch (average / 10) {
        case 10: case 9: puts("Grade A"); break;
        case 8: puts("Grade B"); break;
        default: puts("Keep practicing");
    }
    return 0;
}
Result of running the code
Grade B
C++
Run code →
main.cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> scores{92, 71, 84};
    int total = 0;
    for (int score : scores) total += score;
    switch ((total / static_cast<int>(scores.size())) / 10) {
        case 10: case 9: std::cout << "Grade A\n"; break;
        case 8: std::cout << "Grade B\n"; break;
        default: std::cout << "Keep practicing\n";
    }
}
Result of running the code
Grade B

C and C++ comparison

The syntax is largely shared. Prefer braces even for one statement, ensure switch cases do not fall through accidentally, and keep loop bounds within the array.

C

C exposes small procedural APIs and makes representation details explicit.

C++

C++ retains the low-level model while adding safer library types and abstractions.

Practice exercises

Run both versions, then modify them to observe the different language guarantees.

  • Add invalid and boundary-value inputs.
  • Compile with -Wall -Wextra -Wpedantic.
  • Move reusable declarations into a header and implementation file.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges