Control Flow and Functions
Control Flow and Functions
Use `if`, loops, and reusable functions to organize program behavior.
Control Flow and Functions
Use `if`, loops, and reusable functions to organize program behavior.
ifif (temperature > 30) {
std::cout << "Hot\n";
} else {
std::cout << "Not hot\n";
}
for (int i = 1; i <= 5; ++i) {
std::cout << i << '\n';
}
int square(int x) {
return x * x;
}
#include <iostream>
bool is_even(int value) {
return value % 2 == 0;
}
int main() {
for (int i = 1; i <= 10; ++i) {
if (is_even(i)) {
std::cout << i << " is even\n";
}
}
}
switch and enum classenum class MenuChoice { add, remove, quit };
void handle(MenuChoice choice) {
switch (choice) {
case MenuChoice::add:
add_item();
break;
case MenuChoice::remove:
remove_item();
break;
case MenuChoice::quit:
shutdown();
break;
}
}
This keeps control flow readable when the set of cases is closed and explicit.
int and double by value.const&.Refactor a loop-heavy program into three functions: input, computation, and output. The goal is to make main() read like a summary of the program.