Control Flow: Branching and Looping Constructs
Single-Branch Selection
Executes a statement or block if a condition evaluates to true.
if (condition) {
// Code to execute if condition is true
}
Example: Check if a number is positive.
int number = 10;
if (number > 0) {
// This block will run
}
Dual-Branch Selection
Provides an alternative path when the initial condition is false.
if (condition) {
// Code for true case
} else {
// Code for false case
}
Example: Determine if a number is even or odd.
int value = 7;
if (value % 2 == 0) {
// Even
} else {
// Odd
}
Multi-Branch Selection
Chains multiple conditions to handle several cases.
if (condition1) {
// Case 1
} else if (condition2) {
// Case 2
} else {
// Default case
}
Switch Statement
Evaluates an integer expression and jumps to a matching case label.
switch (expression) {
case constant1:
// Code for case 1
break;
case constant2:
// Code for case 2
break;
default:
// Code if no case matches
}
The break statement prevents fall-through to subsequent cases.
While Loop
Repeats a block of code as long as a condition remains true. The condition is checked before each iterration.
while (condition) {
// Loop body
}
Example: Summing integers from 1 to 5.
int idx = 1, total = 0;
while (idx <= 5) {
total += idx;
idx++;
}
For Loop
A compact loop structure combining initialization, condition, and update.
for (init; condition; update) {
// Loop body
}
Example: Print numbers from 0 to 4.
for (int i = 0; i < 5; i++) {
// Print i
}
Do-While Loop
Executes the loop body once before checking the condition. Ensures the body runs at least once.
do {
// Loop body
} while (condition);
Example: Read input until a sentinel value is entered.
int input;
do {
// Read input
} while (input != -1);
Loop Control Statements
break: Immediately exits the innermots loop.continue: Skips the remainder of the current iteration and proceeds to the next one.
Clearing Input Buffer
A common pattern to discard remaining characters in the input buffer.
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);