Loops
Loops in C: while, do-while, for, loop control (break, continue), nested loops, flow of control, and common patterns.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Loops let a program repeat actions efficiently. Engineers use loops to read sensor data streams, process arrays and files, simulate systems over time steps, and automate repetitive calculations.
Key ideas
- Iteration: One complete execution of the loop body is called an iteration.
- Entry-controlled loop: A loop where the condition is checked before entering the body. In C,
forandwhileare entry-controlled. - Exit-controlled loop: A loop where the condition is checked after executing the body once. In C,
do-whileis exit-controlled. - Loop body: The statements that are executed repeatedly.
- Loop control variable (LCV): A variable used to control the number of iterations (for example, the counter
iinfor (i = 0; i < n; i++)). - Termination condition: The logical expression that determines when the loop stops (becomes false for entry-controlled, or fails after the body in exit-controlled).
- Infinite loop: A loop that never terminates during program execution because the termination condition is never reached.
- Loop invariant: A property or assertion that remains true before and after each iteration; useful to reason about correctness (example: in summing the first n numbers, after k iterations, sum == 1 + 2 + … + k).
- Loop control statements: Special statements that alter normal loop flow:
break(exit the nearest loop/switch),continue(skip to the next iteration of the nearest loop), andgoto(jumps to a labeled statement; generally discouraged in structured programming).
Exact statements commonly required in exams:
- Definition: “A loop in C is a control structure that allows repeated execution of a statement or block of statements while a specified condition remains true (entry-controlled) or until a specified condition is checked after the first execution (exit-controlled). Assumption: the loop control variable and condition are defined and updated so that the loop can terminate.”
- Property of entry-controlled loops: “In an entry-controlled loop, the condition is evaluated before the first execution of the body; therefore, if the condition is initially false, the body does not execute even once.”
- Property of exit-controlled loops: “In an exit-controlled loop, the condition is evaluated after the body; therefore, the body executes at least once regardless of the initial condition.”
- Behavior of
break: “breakimmediately terminates execution of the innermost enclosingfor,while,do-whileorswitchand transfers control to the statement following that construct.” - Behavior of
continue: “continueskips the remaining statements in the current iteration of the innermost enclosingfor,while, ordo-while. Infor, it then executes the increment/update expression and re-tests the condition; inwhile/do-while, it re-tests the condition next.” - Typical proof idea using a loop invariant (outline): To prove correctness of a counting loop, show (i) initialization: the invariant holds before the first iteration, (ii) maintenance: if it holds before an iteration, loop code keeps it true after the iteration, (iii) termination: when the condition fails, the invariant plus the negated condition implies the postcondition (desired result).
Flowchart descriptions you can draw and label in exams:
- While loop flowchart: Draw a rounded rectangle labeled “Start”, then a diamond labeled “Condition?”. From the diamond:
- True arrow (yes) to a rectangle “Body” (e.g., process/update). From “Body” an arrow goes back to the diamond.
- False arrow (no) goes to a rounded rectangle “End/Next statement”. Label arrows as “True” and “False”.
- Do-while loop flowchart: Start → rectangle “Body (execute once)” → diamond “Condition?”. From the diamond:
- True arrow back to the body rectangle.
- False arrow to End. Add a note “condition checked after body”.
- For loop flowchart: Start → rectangle “Initialization” → diamond “Condition?” → if True → rectangle “Body” → rectangle “Update” → back to diamond; if False → End. Label clearly: Initialization (once), Condition (each iteration), Update (after body).
Choosing a loop (guideline):
- Use
forwhen the number of iterations is known or count-controlled (e.g., iterate from 1 to N). - Use
whilewhen you iterate until a condition becomes false and the first execution depends on the condition (e.g., read until EOF or until a threshold is reached). - Use
do-whilewhen you must execute the body at least once (e.g., input menu that should show once before checking to continue).
Nested loops:
- Definition: A loop inside the body of another loop is a nested loop. The inner loop completes all its iterations for each single iteration of the outer loop. Total iterations = product of iteration counts if both are count-controlled.
Time complexity (informal, links to Algorithms topic):
- A simple loop that runs N times has time complexity O(N). A nested loop with outer N and inner M runs O(N·M). Memory usage is typically O(1) unless additional data structures are created.
Safe looping practices:
- Initialize the LCV before use.
- Ensure the condition will eventually become false (update the LCV correctly) to avoid infinite loops unless intentionally used (e.g., in event loops with
break). - For floating-point conditions, avoid equality checks due to precision; use comparisons with tolerance (see Operators and expressions topic for floating-point issues).
- Be careful with unsigned loop counters when counting down; conditions like i >= 0 are always true for unsigned types and can cause infinite loops. Prefer signed integers for such loops or use a different termination condition.
Formulas
- Checks condition first; executes statement/body while condition is true.
while (condition) { statements }- Block form; recommended for multiple statements.
do statement; while (condition);- Executes statement once, then repeats while condition is true. Note the required semicolon after the while.
do { statements } while (condition);- Block form of do-while.
for (initialization; condition; update) statement;- Initialization runs once; condition checked before each iteration; update runs after each iteration’s body. In C99 and later, you may declare the loop variable in the initialization (e.g., for (int i = 0; ...)); its scope is limited to the for loop; in older C (C90), declare the variable before the loop.
for (init_expr_list; condition; update_expr_list) { statements }- Multiple init or update expressions may be comma-separated.
break;- Exits nearest loop or switch immediately.
continue;- Skips to next iteration (runs update first in
for).
- Skips to next iteration (runs update first in
for (;;)- Infinite loop (no condition). Typically combined with
breakto exit.
- Infinite loop (no condition). Typically combined with
while (1) { … }- Infinite loop using a constant true condition.
Worked examples
Example 1: Sum of first N natural numbers using a for loop (entry-controlled)
Code:
#include <stdio.h>
int main(void) {
int N;
long long sum = 0; // use a wider type to reduce overflow risk for large N
printf("Enter a positive integer N: ");
if (scanf("%d", &N) != 1) {
printf("Invalid input.\n");
return 0;
}
if (N <= 0) {
printf("N must be positive.\n");
return 0;
}
for (int i = 1; i <= N; i++) {
sum += i;
}
printf("Sum of first %d natural numbers = %lld\n", N, sum);
return 0;
}
Sample input:
10
Exact output:
Enter a positive integer N: 10
Sum of first 10 natural numbers = 55
Example 2: Factorial using a while loop (entry-controlled; demonstrates initialization, condition, update)
Code:
#include <stdio.h>
int main(void) {
int n;
unsigned long long fact = 1ULL; // factorial grows fast; this still overflows for large n
printf("Enter a non-negative integer n: ");
if (scanf("%d", &n) != 1) {
printf("Invalid input.\n");
return 0;
}
if (n < 0) {
printf("n must be non-negative.\n");
return 0;
}
int i = 1; // initialization
while (i <= n) { // condition
fact = fact * i; // body
i = i + 1; // update
}
printf("%d! = %llu\n", n, fact);
return 0;
}
Sample input:
5
Exact output:
Enter a non-negative integer n: 5
5! = 120
Example 3: Using do-while with break and continue to sum positive integers until 0 is entered
Code:
#include <stdio.h>
int main(void) {
long long sum = 0;
int x;
do {
printf("Enter an integer (0 to stop): ");
if (scanf("%d", &x) != 1) {
printf("Invalid input. Exiting.\n");
break; // cannot continue safely
}
if (x < 0) {
printf("Negative ignored.\n");
continue; // skip adding and go to next iteration
}
if (x == 0) {
break; // exit loop
}
sum += x;
} while (1); // exit-controlled style ensures body ran at least once
printf("Sum of positive integers = %lld\n", sum);
return 0;
}
Sample input:
5
-3
7
0
Exact output:
Enter an integer (0 to stop): 5
Enter an integer (0 to stop): -3
Negative ignored.
Enter an integer (0 to stop): 7
Enter an integer (0 to stop): 0
Sum of positive integers = 12
Notes on correctness:
- In Example 1, the for loop runs i = 1, 2, …, 10, adding each to sum; final sum is 55.
- In Example 2, while loop multiplies 1·2·3·4·5 = 120.
- In Example 3, negatives are skipped; 5 + 7 = 12; loop ends when 0 is read; prompts and messages appear in the shown order.
Common mistakes
- Forgetting to update the LCV: Causes infinite loops (e.g.,
while (i < n)withouti++). - Using
=instead of==in conditions: Assigns instead of compares, often creating infinite loops or wrong behavior. - Misplacing semicolons: Writing
while (condition); { … }adds an empty loop and the block always executes once after the loop, which is wrong. - Forgetting the semicolon in
do { … } while (condition);which is required. - Assuming
continuein aforskips the update: In C, aftercontinuein afor, the update expression still executes. - Not initializing the accumulator or counter: Using garbage initial values yields incorrect results.
- Overflow with factorial or sums: Using
intfor large results; factorial overflows even 64-bit quickly (e.g., 21! exceeds 64-bit unsigned). Mention limits or use bigger types/libraries when needed. - Reading inputs without checking
scanfreturn value: Leads to undefined behavior if input is non-numeric and variables remain unchanged. - Floating-point loop conditions with equality:
while (x != 1.0)can loop forever due to precision; use comparisons with a tolerance. - Nested loops: Forgetting to reset inner-loop indices or counters at the correct time.
For your exam
- Diagrams: Draw and label while/do-while/for flowcharts. For full marks, include Start/End, Condition diamond with True/False arrows, and correct order (Initialization → Condition → Body → Update for for-loop).
- Trace/hand-simulation: Given a snippet, list the sequence of values of variables each iteration and the final output. For full marks, show a table of iteration number, key variables, and condition truth value.
- Programs: Write a program to compute a series sum, factorial, Fibonacci sequence (iterative), print a pattern with nested loops, or process an array with loops (arrays topic). For full marks, include headers, correct loop choice, initialization, termination condition, updates, input validation, and exact formatted output.
- Reasoning: Explain why a loop terminates (mention update and condition), or prove correctness using a simple invariant. For full marks, state the invariant and show initialization, maintenance, and termination.
- Complexity: State the time complexity of a given loop or nested loops. For full marks, count iterations and state O-notation with clear reasoning.
Quick check
- Which C loop guarantees the body runs at least once, and why?
- What does
continuedo differently in aforloop compared to awhileloop? - Identify the error:
while (i < n); { sum += a[i]; i++; }
Answers: 1) do-while, because the condition is tested after executing the body once (exit-controlled). 2) In a for, after continue, the update expression runs before re-testing the condition; in a while, control goes directly to re-test the condition without any automatic update. 3) The stray semicolon after the condition creates an empty loop; the block runs once after the loop, not as part of it.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?