Search Knowledge

© 2026 LIBREUNI PROJECT

C Programming Mastery / Program Logic

Iteration and Loop Mechanisms

Iteration in C

Iteration allows a program to repeat a block of code while a condition is met. C provides three primary loop constructs: while, do-while, and for.

The while vs. do-while

The fundamental difference lies in when the condition is evaluated.

  • while: Pre-test loop. The body may execute zero times.
  • do-while: Post-test loop. The body is guaranteed to execute at least once. This is often used for input validation or state machines where an action must be performed before its result can be checked.
int i = 10;
while (i < 5) { /* Never runs */ }

do {
    /* Runs exactly once */
} while (i < 5);

The Versatile for Loop

The for loop is syntactically sugar for a while loop but is much more expressive. It consists of three expressions:

  1. Initialization: Executed once before the loop starts.
  2. Condition: Evaluated before each iteration.
  3. Stepper: Evaluated at the end of each iteration.

The Comma Operator in Loops

C’s comma operator allows you to include multiple expressions where only one is expected. This is particularly useful in for loops for managing multiple counters.

for (int i = 0, j = 10; i < j; i++, j--) {
    printf("i: %d, j: %d\n", i, j);
}

Loop Control: break and continue

  • break: Immediately terminates the innermost loop.
  • continue: Skips the remainder of the current iteration and jumps to the condition/stepper evaluation.

Warning: Overusing break and continue can lead to “spaghetti code.” Use them judiciously to handle exceptional cases rather than as primary control logic.

Infinite Loops and Machine Behavior

In systems programming, infinite loops are often intentional (e.g., an OS kernel idle loop or an embedded control loop).

for (;;) { /* The idiomatic C infinite loop */ }
while (1) { /* Also common */ }

Optimization: Loop Unrolling

High-performance C relies on the compiler to optimize loops. Loop Unrolling is a technique where the compiler replicates the loop body multiple times to reduce the overhead of the condition check and the branch.

Manually unrolling:

// Standard
for (int i = 0; i < 4; i++) { process(i); }

// Unrolled (conceptually)
process(0); process(1); process(2); process(3);

Modern compilers like GCC and Clang will do this automatically if they determine it will improve performance without blowing up the code size (cache pressure).

Interactive Lab

Loop Evaluation

int i = 0;
while (i < 3) {
    printf("%d", i);
    ;
}
Runtime Environment

Interactive Lab

1#include <stdio.h>
2 
3int main() {
4 // Calculating factorials via iteration
5 int n = 5;
6 long long fact = 1;
7 for(int i = 1; i <= n; i++) {
8 fact *= i;
9 }
10 printf("Factorial of %d is %lld\n", n, fact);
11 return 0;
12}
System Console

Waiting for signal...