Loops in C
Repeat actions automatically! Master for, while, and do-while loops. Learn which loop to use when, and how to control loops with break and continue.
Track Your Progress
Sign in to save your learning progress
What You Will Learn
- ✓Use for loops when you know the count
- ✓Use while loops when you have a condition
- ✓Use do-while when you need at least one execution
- ✓Control loops with break and continue
01Why Do We Need Loops?
Simple Definition
A loop repeats a block of code multiple times. Instead of writing the same code 100 times, you write it once inside a loop!
How a Loop Works
Without Loop (5 lines!)
printf("Hello\n");
printf("Hello\n");
printf("Hello\n");
printf("Hello\n");
printf("Hello\n");✓With Loop (3 lines!)
for (int i = 0; i < 5; i++) {
printf("Hello\n");
}Three Types of Loops in C
for
When you know how many times
Count from 1 to 10
while
When you don't know how many times
Until user enters 0
do-while
Must run at least once
Show menu, then ask
02Loop Conditions
Every loop depends on a condition that determines when the loop should stop.
Quick Reminder: True and False in C
In C: 0 = FALSE (loop exits) and any non-zero = TRUE (loop continues).
For detailed explanation, see Control Flow Tutorial.
Common Loop Conditions
| Expression | Value | Result | Loop Behavior |
|---|---|---|---|
| 0 | 0 | FALSE | Loop doesn't run / exits |
| 1 | 1 | TRUE | Loop runs / continues |
| -5 | -5 (non-zero) | TRUE | Loop runs / continues |
| 100 | 100 (non-zero) | TRUE | Loop runs / continues |
| 5 > 3 | 1 | TRUE | Loop runs / continues |
| 5 < 3 | 0 | FALSE | Loop doesn't run / exits |
| '\0' (null char) | 0 | FALSE | Loop doesn't run / exits |
| NULL pointer | 0 | FALSE | Loop doesn't run / exits |
▶ Try it: Demonstrates how C interprets different values as true or false in loop conditions.
1#include <stdio.h>23int main() {4 // Demonstrating true/false values5 printf("Testing loop conditions:\n\n");6 7 // while(0) - FALSE, never runs8 printf("while(0): ");9 while (0) {10 printf("This never prints");11 }12 printf("Skipped (0 is FALSE)\n");13 14 // while(1) runs once with break15 printf("while(1): ");16 while (1) {17 printf("Runs! (1 is TRUE)\n");18 break;19 }20 21 // Negative numbers are TRUE22 int x = -5;23 printf("while(-5): ");24 while (x) {25 printf("Runs! (-5 is TRUE, non-zero)\n");26 break;27 }28 29 // Comparison results30 printf("\nComparison expressions:\n");31 printf("5 > 3 evaluates to: %d (TRUE)\n", 5 > 3);32 printf("5 < 3 evaluates to: %d (FALSE)\n", 5 < 3);33 printf("5 == 5 evaluates to: %d (TRUE)\n", 5 == 5);34 35 return 0;36}Testing loop conditions:
while(0): Skipped (0 is FALSE)
while(1): Runs! (1 is TRUE)
while(-5): Runs! (-5 is TRUE, non-zero)
Comparison expressions:
5 > 3 evaluates to: 1 (TRUE)
5 < 3 evaluates to: 0 (FALSE)
5 == 5 evaluates to: 1 (TRUE)
Common Idiom: while(1) for Infinite Loops
Since any non-zero value is true, while(1) creates an infinite loop. Use break to exit when needed.
03While Loop
The while loop checks the condition first. If the condition is false from the start, the loop never runs.
While Loop Syntax
}
Check condition → If true, run body → Repeat
1.Simple Counting
#include <stdio.h>int main() { int i = 1; while (i <= 5) { printf("%d ", i); i++; // Don't forget this! } return 0;}2.Sum Until Zero
#include <stdio.h>int main() { int num, sum = 0; printf("Enter numbers (0 to stop):\n"); scanf("%d", &num); while (num != 0) { sum += num; scanf("%d", &num); } printf("Sum: %d\n", sum); return 0;}Input: 5 10 3 0
Sum: 18
When to Use While
- • You don't know how many times to loop
- • Loop depends on user input or external data
- • Reading until end of file
Common Bug: Infinite Loop!
Always update your loop variable! Forgetting creates an endless loop.
Missing i++
while (i < 5) {
printf("%d", i);
}
✓Correct
while (i < 5) {
printf("%d", i);
i++;
}
04For Loop (The Counter Loop)
The for loop is the most commonly used loop. It puts initialization, condition, and update all in one line, making it perfect for counting.
For Loop Syntax
① Init
Run once at start
int i = 0
② Condition
Check before each run
i < 5
③ Update
Run after each loop
i++
1.Count from 1 to 5
#include <stdio.h>int main() { for (int i = 1; i <= 5; i++) { printf("%d ", i); } return 0;}2.Count Down from 5 to 1
#include <stdio.h>int main() { for (int i = 5; i >= 1; i--) { printf("%d ", i); } printf("Blast off!\n"); return 0;}3.Skip by 2 (Even Numbers)
#include <stdio.h>int main() { for (int i = 2; i <= 10; i += 2) { printf("%d ", i); } return 0;}C99 Feature: Declare Variable in Loop
Since C99, you can declare the loop variable inside the for statement. The variable only exists inside the loop (better scope control).
Old style (C89)
int i;
for (i = 0; ...)
✓Modern (C99+)
for (int i = 0; ...)
Step-by-Step Execution
For: for (int i = 0; i < 3; i++)
Step 1: Init i = 0
Step 2: Check 0 < 3? ✓ TRUE → Run body
Step 3: Update i++ → i = 1
Step 4: Check 1 < 3? ✓ TRUE → Run body
Step 5: Update i++ → i = 2
Step 6: Check 2 < 3? ✓ TRUE → Run body
Step 7: Update i++ → i = 3
Step 8: Check 3 < 3? ✗ FALSE → Exit loop
Execution Order (Step by Step)
1. Initialization: int i = 0
2. Check condition: i < 3 → 0 < 3 = TRUE
3. Execute body: printf(i) → prints 0
4. Update: i++ → i becomes 1
5. Check condition: i < 3 → 1 < 3 = TRUE
... (continues until i = 3, then 3 < 3 = FALSE, loop ends)
When to Use For Loop
| ✓Use For When | Don't Use When |
|---|---|
| You know exact number of iterations | Iterations depend on runtime input |
| Counting from A to B | Waiting for external condition |
| Iterating through array elements | Complex state-based loops |
| Nested counting (2D arrays, patterns) | Loop must run at least once |
▶ Try it: Demonstrates common for loop patterns: counting up, counting down, and skipping values.
1#include <stdio.h>23int main() {4 // Pattern 1: Count up (0 to 4)5 printf("Count up: ");6 for (int i = 0; i < 5; i++) {7 printf("%d ", i);8 }9 printf("\n");10 11 // Pattern 2: Count down (5 to 1)12 printf("Count down: ");13 for (int i = 5; i >= 1; i--) {14 printf("%d ", i);15 }16 printf("\n");17 18 // Pattern 3: Skip values (even numbers)19 printf("Even numbers: ");20 for (int i = 0; i <= 10; i += 2) {21 printf("%d ", i);22 }23 printf("\n");24 25 // Pattern 4: Multiple variables26 printf("Two counters: ");27 for (int i = 0, j = 10; i < j; i++, j--) {28 printf("(%d,%d) ", i, j);29 }30 printf("\n");31 32 return 0;33}Count up: 0 1 2 3 4
Count down: 5 4 3 2 1
Even numbers: 0 2 4 6 8 10
Two counters: (0,10) (1,9) (2,8) (3,7) (4,6)
05Nested Loops
A nested loop is a loop inside another loop. The inner loop completes all its iterations for each iteration of the outer loop.
Total Iterations = Outer × Inner
If outer loop runs 3 times
and inner loop runs 4 times
Total = 3 × 4 = 12 inner iterations
▶ Try it: Prints a multiplication table using nested loops.
1#include <stdio.h>23int main() {4 printf("Multiplication Table (1-5):\n\n");5 6 // Print header row7 printf(" ");8 for (int j = 1; j <= 5; j++) {9 printf("%4d", j);10 }11 printf("\n --------------------\n");12 13 // Outer loop: rows (1 to 5)14 for (int i = 1; i <= 5; i++) {15 printf("%d | ", i);16 17 // Inner loop: columns (1 to 5)18 for (int j = 1; j <= 5; j++) {19 printf("%4d", i * j);20 }21 printf("\n");22 }23 24 return 0;25}Multiplication Table (1-5):
1 2 3 4 5
--------------------
1 | 1 2 3 4 5
2 | 2 4 6 8 10
3 | 3 6 9 12 15
4 | 4 8 12 16 20
5 | 5 10 15 20 25
▶ Try it: Creates a triangle pattern using nested loops.
1#include <stdio.h>23int main() {4 int rows = 5;5 6 printf("Right Triangle Pattern:\n");7 8 for (int i = 1; i <= rows; i++) {9 // Inner loop runs 'i' times each row10 for (int j = 1; j <= i; j++) {11 printf("* ");12 }13 printf("\n");14 }15 16 return 0;17}Right Triangle Pattern:
*
* *
* * *
* * * *
* * * * *
06Do-While Loop (Exit-Controlled)
The do-while loop checks the condition after each iteration. This guarantees the loop body runs at least once, even if the condition is initially false.
Syntax & Flow
do {
// code runs at least once
} while (condition); // ← Semicolon!Flow:
Execute → Check → Repeat
↑ If condition TRUE
When to Use Do-While Loop
| ✓Use Do-While When | Don't Use When |
|---|---|
| Loop must execute at least once | You might not need any iterations |
| Menu systems (show menu first) | Simple counting tasks |
| Input validation (get input, then check) | Iterating through arrays |
| Game loops (play, then ask continue?) | Reading files that might be empty |
▶ Try it: Validates user input using do-while - keeps asking until valid input is received.
1#include <stdio.h>23int main() {4 int age;5 6 // Input validation with do-while7 do {8 printf("Enter your age (1-120): ");9 scanf("%d", &age);10 11 if (age < 1 || age > 120) {12 printf("Invalid age! Please try again.\n");13 }14 } while (age < 1 || age > 120);15 16 printf("\nValid age entered: %d\n", age);17 18 if (age >= 18) {19 printf("You are an adult.\n");20 } else {21 printf("You are a minor.\n");22 }23 24 return 0;25}Enter your age (1-120): -5
Invalid age! Please try again.
Enter your age (1-120): 150
Invalid age! Please try again.
Enter your age (1-120): 25
Valid age entered: 25
You are an adult.
While vs Do-While Comparison
while (condition FALSE)
int x = 10;
while (x < 5) {
printf("Hi");
}
// Prints: NOTHINGdo-while (condition FALSE)
int x = 10;
do {
printf("Hi");
} while (x < 5);
// Prints: Hi (once)07Break, Continue, and Goto
These jump statements give you control over loop execution flow.
| Statement | Effect | Common Use |
|---|---|---|
| break | Exit loop immediately | Found what you need, stop searching |
| continue | Skip to next iteration | Skip unwanted items, keep looping |
| goto | Jump to labeled statement | Avoid! (breaks out of nested loops) |
▶ Try it: Demonstrates break (finding a number) and continue (skipping values).
1#include <stdio.h>23int main() {4 // BREAK: Exit loop when target found5 printf("Finding first multiple of 7 (1-20):\n");6 for (int i = 1; i <= 20; i++) {7 if (i % 7 == 0) {8 printf("Found: %d\n", i);9 break; // Stop searching10 }11 printf("%d ", i);12 }13 14 // CONTINUE: Skip certain values15 printf("\nOdd numbers from 1-10:\n");16 for (int i = 1; i <= 10; i++) {17 if (i % 2 == 0) {18 continue; // Skip even numbers19 }20 printf("%d ", i);21 }22 printf("\n");23 24 return 0;25}Finding first multiple of 7 (1-20):
1 2 3 4 5 6 Found: 7
Odd numbers from 1-10:
1 3 5 7 9
About goto
goto jumps to a labeled statement. It's considered bad practice because it creates "spaghetti code" that's hard to follow. See Control Flow Tutorial for more details.
Acceptable use of goto: breaking out of multiple nested loops at once.
1#include <stdio.h>23int main() {4 // Finding coordinates in a 2D search5 printf("Searching for (2,2) in 4x4 grid:\n");6 7 for (int i = 0; i < 4; i++) {8 for (int j = 0; j < 4; j++) {9 printf("Checking (%d,%d)\n", i, j);10 if (i == 2 && j == 2) {11 printf(">>> FOUND! <<<\n");12 goto found; // Exit BOTH loops13 }14 }15 }16 printf("Not found.\n");17 goto end;18 19 found:20 printf("Search complete - target located.\n");21 22 end:23 return 0;24}Searching for (2,2) in 4x4 grid:
Checking (0,0)
... (continues through grid)
Checking (2,1)
Checking (2,2)
>>> FOUND! <<<
Search complete - target located.
08Infinite Loops
Sometimes you intentionally create a loop that runs forever. Use break to exit when a condition is met.
Common Infinite Loop Patterns
while(1)
Most common
for(;;)
Empty for loop
while(true)
With stdbool.h
▶ Try it: Implements a simple calculator menu using an infinite loop.
1#include <stdio.h>23int main() {4 int choice, a, b;5 6 while (1) { // Infinite loop7 printf("\n=== Calculator ===\n");8 printf("1. Add\n");9 printf("2. Subtract\n");10 printf("3. Multiply\n");11 printf("4. Exit\n");12 printf("Choice: ");13 scanf("%d", &choice);14 15 if (choice == 4) {16 printf("Goodbye!\n");17 break; // Exit infinite loop18 }19 20 if (choice < 1 || choice > 4) {21 printf("Invalid choice!\n");22 continue; // Skip to next iteration23 }24 25 printf("Enter two numbers: ");26 scanf("%d %d", &a, &b);27 28 switch (choice) {29 case 1: printf("Result: %d\n", a + b); break;30 case 2: printf("Result: %d\n", a - b); break;31 case 3: printf("Result: %d\n", a * b); break;32 }33 }34 35 return 0;36}=== Calculator ===
1. Add
2. Subtract
3. Multiply
4. Exit
Choice: 1
Enter two numbers: 10 5
Result: 15
... (menu repeats)
09Looping Through Arrays
One of the most common uses of loops is iterating through arrays. Here are the best practices.
1.Basic Array Iteration
#include <stdio.h>int main() { int numbers[] = {10, 20, 30, 40, 50}; int size = 5; for (int i = 0; i < size; i++) { printf("numbers[%d] = %d\n", i, numbers[i]); } return 0;}numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
...
2.Calculate Array Size with sizeof
#include <stdio.h>int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7}; // Calculate size automatically int size = sizeof(arr) / sizeof(arr[0]); printf("Array has %d elements:\n", size); for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } return 0;}Array has 7 elements:
1 2 3 4 5 6 7
sizeof(arr)/sizeof(arr[0]) = total bytes / bytes per element = number of elements
3.Looping Through a String
#include <stdio.h>int main() { char str[] = "Hello"; // Method 1: Using index for (int i = 0; str[i] != '\0'; i++) { printf("%c ", str[i]); } printf("\n"); // Method 2: Using pointer for (char *p = str; *p != '\0'; p++) { printf("%c ", *p); } return 0;}H e l l o
H e l l o
Best Practice: Use size_t for Array Indices
For array sizes and indices, use size_t (from <stddef.h> or <stdlib.h>). It's an unsigned type that can hold any array size.
#include <stddef.h>
size_t size = sizeof(arr) / sizeof(arr[0]);
for (size_t i = 0; i < size; i++) { ... }
10Choosing the Right Loop
Use this decision guide to pick the best loop for your situation:
Loop Selection Flowchart
| Scenario | Best Loop | Why |
|---|---|---|
| Print numbers 1 to 100 | for | Known count, simple increment |
| Iterate through array | for | Array size is known |
| Read until end of file | while | Unknown iterations, file may be empty |
| Sum numbers until user enters 0 | while | Unknown how many numbers |
| Menu system | do-while | Must show menu at least once |
| Validate user input | do-while | Get input first, then validate |
| Game loop | while(1) + break | Runs until player quits |
| 2D pattern / matrix | nested for | Rows and columns both known |
!Code Pitfalls: Common Mistakes & What to Watch For
These are the most common loop mistakes that trip up beginners. Study them carefully to avoid hours of debugging!
Infinite loop - forgetting to update loop variable
The most common loop bug! If the condition never becomes false, the loop runs forever.
// WRONG - i never changes, loops forever!int i = 0;while (i < 5) { printf("%d\n", i); // Missing i++; }// CORRECTint i = 0;while (i < 5) { printf("%d\n", i); i++; // Update the loop variable!}Off-by-one error
Looping one too many or one too few times. Check your boundaries!
int arr[5] = {1, 2, 3, 4, 5};// WRONG - accesses arr[5] which doesn't exist!for (int i = 0; i <= 5; i++) { // Should be i < 5 printf("%d ", arr[i]);}// CORRECT - array indices 0 to 4for (int i = 0; i < 5; i++) { printf("%d ", arr[i]);}Semicolon after for/while
A semicolon creates an empty loop body!
// WRONG - semicolon makes loop body emptyfor (int i = 0; i < 5; i++); // Loop does nothing{ printf("%d\n", i); // Only runs once, i = 5}// CORRECTfor (int i = 0; i < 5; i++) { // No semicolon! printf("%d\n", i);}Modifying loop variable inside loop
Changing the loop counter inside the loop body causes unpredictable behavior.
// WRONG - modifying i inside loopfor (int i = 0; i < 10; i++) { printf("%d ", i); if (i == 5) { i = 8; // Skips 6, 7 - confusing! }}// BETTER - use continue or break for controlfor (int i = 0; i < 10; i++) { if (i >= 6 && i <= 7) { continue; // Skip 6 and 7 clearly } printf("%d ", i);}Using = instead of == in condition
Assignment in condition causes unexpected behavior!
int x = 0;// WRONG - assigns 1 to x, always true!while (x = 1) { // Should be x == 1 printf("Infinite loop!\n");}// CORRECTwhile (x == 1) { printf("x is 1\n");}Wrong loop type for the task
Using while when you need do-while, or for when while is clearer.
// WRONG - duplicated code to show menu firstprintf("Menu...\n");scanf("%d", &choice);while (choice != 0) { process(choice); printf("Menu...\n"); // Duplicated! scanf("%d", &choice);}// CORRECT - do-while shows menu at least oncedo { printf("Menu...\n"); scanf("%d", &choice); if (choice != 0) process(choice);} while (choice != 0);Missing semicolon after do-while
Unlike for and while, do-while requires a semicolon at the end!
// WRONG - missing semicolondo { printf("Hello\n");} while (condition) // ERROR! Missing ;// CORRECTdo { printf("Hello\n");} while (condition); // Semicolon required!Watch Out When Copying Loop Code!
Loops are where copied code makes its most dangerous mistakes because off-by-one errors can go unnoticed until runtime.
Off-By-One Errors
Copied code often uses <= instead of <, causing array out-of-bounds access.
Infinite Loop Conditions
Watch for conditions that never become false, especially with unsigned integers where i >= 0 is always true.
Missing Loop Updates
In while loops, beginners often place the increment in the wrong place or forget it entirely.
Your Defense: Always trace loop boundaries manually. Ask: "What's the first value? What's the last value? Does the loop stop correctly?"
13Frequently Asked Questions
Q:When should I use for vs while vs do-while?
A: Use for when you know exactly how many times to loop (iterating arrays, counting to N). Use while when you don't know the count — you loop until a condition changes (reading until EOF, waiting for user input). Use do-while when the loop must run at least once (menu systems, input validation where you need to get input before checking it).
Q:Why do loops use i, j, k as variable names?
A: This convention comes from mathematics, where i, j, k are traditionally used for indices and iteration variables. In early Fortran, variables starting with I-N were automatically integers, making i, j, k natural choices. The convention stuck because it's universally understood. For better readability in complex loops, use meaningful names likerow, col, oridx.
Q:What's the difference between break and continue?
A: break exits the entire loop immediately — no more iterations run. continueskips the rest of the current iteration and jumps to the next one. Think of break as "I'm done completely" and continue as "skip this one, try the next." Both only affect the innermost loop they're in.
Q:Why is do-while rarely used?
A: Most loops naturally check conditions before running. Do-while's "run first, check later" pattern is only needed in specific cases: menu systems (show menu at least once), input validation (need to get input before validating), and some algorithms. When you do need it, do-while is perfect. But for 90%+ of loops, for/while are more natural fits.
Q:Can I have multiple variables in a for loop?
A: Yes! Use commas:for (int i = 0, j = 10; i < j; i++, j--). This initializes both i and j, checks one condition, and updates both. It's useful for two-pointer algorithms or parallel counters. However, don't overuse it — if logic gets complex, a while loop with explicit updates is clearer.
Q:Why does my loop run one time too many (or too few)?
A: This is the famous "off-by-one error" — the most common programming bug! Check: Are you using < vs<=? Starting from 0 or 1? For arrays, always usei < size (not <=). Trace manually: if size=5, i goes 0,1,2,3,4 (5 elements) with <.
Q:How do I exit from nested loops?
A: break only exits the innermost loop. For nested loops, options include: (1) Set a flag variable and check it in the outer loop, (2) Extract the nested loop into a function and use return, (3) Use goto (controversial but sometimes cleanest). Most experienced programmers prefer option 2 — functions make code cleaner anyway.
14Summary
Key Takeaways
- •for: When you know the count →
for (int i = 0; i < n; i++) - •while: When count is unknown →
while (condition) - •do-while: Must run at least once →
do { ... } while (cond); - •break: Exit loop immediately
- •continue: Skip to next iteration
- •Arrays: Use
sizeof(arr)/sizeof(arr[0])for size - •C99+: Declare loop var inside for:
for (int i = 0; ...)
Quick Reference
for loop
for (int i=0; i<n; i++) {
}
while loop
while (condition) {
}
do-while loop
do {
} while (cond);
Test Your Knowledge
Related Tutorials
Control Flow & Decision Making
Make your programs smart! Use if-else to make decisions and switch for multiple choices. Programs can now respond differently to different situations.
Functions in C
Organize code into reusable blocks! Functions let you write code once and use it many times. Learn to create, call, and pass data to functions.
Arrays in C
Store multiple values of the same type together! Learn 1D arrays (lists), 2D arrays (tables), and how arrays are stored in memory.
Have Feedback?
Found something missing or have ideas to improve this tutorial? Let us know on GitHub!