Conditions, Loops, and switch
if chooses by a boolean condition, switch handles discrete cases, and loops repeat a block with explicit termination.
What is Conditions, Loops, and switch?
if chooses by a boolean condition, switch handles discrete cases, and loops repeat a block with explicit termination.
Combine branches and loops in a small classification program.
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.
C and C++ code examples
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;
}
Grade B
C++
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";
}
}
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.