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;
}
Get a Run button for this example 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";
    }
}
Get a Run button for this example 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.

if, else and switch in C and C++

if (x > 0) { ... } else if (x == 0) { ... } else { ... }Check conditions in order
==, !=, <, <=, >, >=Comparison operators
&&, ||, !And, or, not (evaluated left to right, stopping as soon as the result is known)
result = (a > b) ? a : b;Ternary operator: a short if/else that returns a value
switch (day) { case 1: ...; break; default: ...; }Choose between many integer or char values
case 6: case 7: puts("weekend"); break;Several cases can share one block
[[fallthrough]];C++17: mark an intentional fall-through to the next case
if (int n = f(); n > 0)C++17: declare a variable used only by the if

Common mistakes with if and switch

Using = instead of ==

= assigns, so if (x = 5) is always true and changes x. Turn on warnings (-Wall) to catch it.

Problem
int x = 3;
if (x = 5) {           /* always true, x is now 5 */
    printf("five\n");
}
Fix
int x = 3;
if (x == 5) {
    printf("five\n");
}

Forgetting break in a switch

Without break, execution falls through into the next case.

Problem
switch (grade) {
    case 'A': printf("Excellent\n");
    case 'B': printf("Good\n");   /* also printed for 'A' */
}
Fix
switch (grade) {
    case 'A': printf("Excellent\n"); break;
    case 'B': printf("Good\n"); break;
}

A semicolon right after if

if (cond); ends the if immediately, so the block below always runs.

Problem
if (score > 90);
{
    printf("A\n");          /* runs for every score */
}
Fix
if (score > 90) {
    printf("A\n");
}

Frequently asked questions

What is the difference between if-else and switch?

if-else can test any condition, including ranges and several variables. switch compares one integer, char or enum value against constant cases, which is clearer and can be faster when there are many cases.

Can I use strings in a switch statement?

No. In C and C++, switch works with integer types, chars and enums only. Use if-else with strcmp in C, or == with std::string in C++.

What does the ternary operator do?

condition ? a : b returns a when the condition is true and b otherwise, for example int max = (x > y) ? x : y;.

Why does my switch run several cases?

A case without break falls through into the next one. Add break at the end of each case unless the fall-through is intended.

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