C Basics
Loops & Iteration
Loops allow you to run a block of code repeatedly as long as a specified condition remains true. C offers three loop constructs.
1. The While Loop
Evaluates the condition before executing the loop body. If the condition is false initially, the loop body is never executed:
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++; // Don't forget to update loop variable to avoid infinite loops
}
// Output: 1 2 3 4 5
2. The Do-While Loop
Evaluates the condition after executing the loop body. This guarantees that the loop body executes at least once:
#include <stdio.h>
int main() {
int password_guess;
int correct_password = 1234;
do {
printf("Enter password code: ");
scanf("%d", &password_guess);
} while (password_guess != correct_password);
printf("Access granted.\n");
return 0;
}
3. The For Loop
A clean, compact loop structure that groups initialization, condition evaluation, and variable update into one line:
for (int i = 0; i < 5; i++) {
printf("Count: %d\n", i);
}
4. Break and Continue
break: Terminating statement that immediately exits the loop block.continue: Skips the remaining statements in the current iteration and jumps directly to the next condition/iteration update.
for (int i = 1; i <= 6; i++) {
if (i == 5) {
break; // Stops loop completely
}
if (i % 2 == 0) {
continue; // Skips printing even numbers
}
printf("%d ", i);
}
// Output: 1 3