Tamil Technicians – C Programming Course · Lesson 8
Loops in C – for, while, do-while Complete Guide (Patterns & Practice)
In previous lessons, we learned variables, operators and control statements like
if, if-else and switch–case.
These help us make decisions once. But very often, a program must
repeat some work many times:
- Read sensor values every second.
- Print a menu again and again until the user chooses “Exit”.
- Generate a pattern of stars or numbers on the screen.
- Scan through 100 readings to find a minimum or maximum.
For this, C gives us loops. In this lesson, we will fully understand
for, while and do-while, and also learn how to
use them to create patterns and practical technician-style programs.
What Is a Loop in C?
A loop is a control structure that repeats a block of code as long as a given condition is true.
Instead of writing the same statements many times:
printf("Hello\\n");
printf("Hello\\n");
printf("Hello\\n");
printf("Hello\\n");
printf("Hello\\n");
We can write a loop that prints “Hello” 5 times:
for (int i = 1; i <= 5; i++) {
printf("Hello\\n");
}
All loops follow the same concept: Initialize → Check condition → Execute body → Update → Repeat.
Types of Loops in C (Beginner Level)
C gives us three main loop types:
forloop – most commonly used when you know the number of repetitions.whileloop – repeats while a condition is true; often used when count is not known in advance.do-whileloop – likewhile, but guarantees the body runs at least once.
Entry-controlled loops
In for and while loops, the condition is checked
before entering the body.
Exit-controlled loop
In a do-while loop, the condition is checked
after executing the body once.
The for Loop in C
The for loop is ideal when we want to repeat something a fixed number of times.
Its syntax packs initialization, condition and
update in one line.
Syntax
for (initialization; condition; update) {
// loop body (statements)
}
- initialization – executed once before the loop starts (e.g.,
int i = 0;). - condition – checked before each iteration; if false, the loop stops.
- update – executed after each iteration (e.g.,
i++;).
Example – Print 1 to 10
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
printf("%d\\n", i);
}
return 0;
}
Flow:
- Set
i = 1. - Check
i <= 10. If true, execute body (print value). - Execute
i++→ increaseiby 1. - Repeat steps 2–3 until condition becomes false.
As a beginner, always mentally track the values of loop variables for the first 3–4 iterations. This helps you understand how the loop behaves.
Example – Sum of First N Natural Numbers
int n, i;
int sum = 0;
printf("Enter n: ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
sum = sum + i; // or sum += i;
}
printf("Sum = %d\\n", sum);
The while Loop in C
The while loop is useful when we do not know in advance
how many times we want to repeat. We just know a condition that must stay true.
Syntax
while (condition) {
// loop body
}
Example – Count down from 5 to 1:
int count = 5;
while (count > 0) {
printf("%d\\n", count);
count--; // update step
}
In this loop:
- Condition is checked before each iteration.
- If condition is already false at the start, the body will not execute even once.
Technician Example – Reading Values Until Stop Code
Imagine reading device status codes until the user enters 0 (stop).
int code;
printf("Enter status code (0 to stop): ");
scanf("%d", &code);
while (code != 0) {
printf("Processing code %d...\\n", code);
// read next code
printf("Enter status code (0 to stop): ");
scanf("%d", &code);
}
printf("Stopped.\\n");
The do-while Loop in C
A do-while loop is similar to while, but the condition is checked
after running the body. This means the body always runs
at least once, even if the condition is false initially.
Syntax
do {
// loop body
} while (condition);
Example – Menu That Must Show at Least Once
int choice;
do {
printf("\\n=== MENU ===\\n");
printf("1. Start\\n");
printf("2. Stop\\n");
printf("3. Status\\n");
printf("0. Exit\\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1: printf("Starting...\\n"); break;
case 2: printf("Stopping...\\n"); break;
case 3: printf("Status OK\\n"); break;
case 0: printf("Exiting...\\n"); break;
default: printf("Invalid choice\\n");
}
} while (choice != 0);
This is a very common pattern: show menu → take input → process → repeat until the user chooses Exit.
for vs while vs do-while – When to Use Which?
| Loop Type | Best Use Case | Condition Check |
|---|---|---|
| for | Known number of iterations (e.g., print first 10 numbers) | Before each iteration (entry-controlled) |
| while | Unknown count, repeat while condition remains true (e.g., read until 0) | Before each iteration (entry-controlled) |
| do-while | Loop must run at least once (e.g., menu, password prompt) | After body executes (exit-controlled) |
If you can easily say “run this block N times”, choose for.
If you say “keep doing this until condition becomes false”, choose while.
If you must run the body at least once, choose do-while.
break and continue in Loops
break – Exit the Loop Immediately
The break statement is used to exit from a loop (or switch) immediately,
regardless of the loop condition.
int i;
for (i = 1; i <= 10; i++) {
if (i == 5) {
break; // stop loop when i becomes 5
}
printf("%d\\n", i);
}
Output: 1 2 3 4
continue – Skip Current Iteration
The continue statement skips the remaining statements in the loop body
for the current iteration and jumps to the next iteration.
int i;
for (i = 1; i <= 5; i++) {
if (i == 3) {
continue; // skip printing when i = 3
}
printf("%d\\n", i);
}
Output: 1 2 4 5
break and continue carefully.
Too many of them can make code harder to follow,
but they are very useful in input validation, search loops, and menus.
Nested Loops – Loops Inside Loops
A nested loop is a loop inside another loop. This is very important for pattern printing and handling 2D structures like tables and matrices.
Example – Print a 3x3 Grid of Numbers
int row, col;
for (row = 1; row <= 3; row++) {
for (col = 1; col <= 3; col++) {
printf("%d ", col);
}
printf("\\n");
}
Output:
1 2 3
1 2 3
1 2 3
Here:
- The outer loop controls the rows.
- The inner loop controls the columns.
Pattern Printing with Loops (Star Patterns)
Pattern programs are a classic way to practice loops. Let’s look at some common examples.
1. Simple Triangle Pattern
For n = 5, output:
*
* *
* * *
* * * *
* * * * *
#include <stdio.h>
int main() {
int n, row, col;
printf("Enter number of rows: ");
scanf("%d", &n);
for (row = 1; row <= n; row++) {
for (col = 1; col <= row; col++) {
printf("* ");
}
printf("\\n");
}
return 0;
}
2. Rectangle of Stars
For 3 rows and 5 columns:
* * * * *
* * * * *
* * * * *
int rows = 3, cols = 5;
int r, c;
for (r = 1; r <= rows; r++) {
for (c = 1; c <= cols; c++) {
printf("* ");
}
printf("\\n");
}
3. Number Triangle
For n = 4, output:
1
1 2
1 2 3
1 2 3 4
int n, row, col;
printf("Enter n: ");
scanf("%d", &n);
for (row = 1; row <= n; row++) {
for (col = 1; col <= row; col++) {
printf("%d ", col);
}
printf("\\n");
}
Practical Loop Examples for Technicians
1. Average of N Readings
int n, i;
float value, sum = 0.0f;
printf("How many readings? ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
printf("Enter reading %d: ", i);
scanf("%f", &value);
sum += value;
}
printf("Average = %.2f\\n", sum / n);
2. Find Maximum Reading
int n, i;
float value, max;
printf("How many readings? ");
scanf("%d", &n);
printf("Enter reading 1: ");
scanf("%f", &max);
for (i = 2; i <= n; i++) {
printf("Enter reading %d: ", i);
scanf("%f", &value);
if (value > max) {
max = value;
}
}
printf("Maximum value = %.2f\\n", max);
Common Mistakes with Loops
- Forgetting to update the loop variable – leads to infinite loops.
- Wrong condition – loop runs one time too many or one time less (off-by-one error).
- Modifying loop variable inside the body in a confusing way.
- Using
;afterfororwhileby mistake:
while (i <= 10); // WRONG: extra semicolon creates empty loop
{
printf("%d\\n", i); // this block is not part of while
}
printf statements
inside the loop to print the loop counter and check the logic.
Loop Debug Checklist
- Is the initialization correct (starting value of counter)?
- Is the condition correct (should it be
<or<=)? - Is the update step correctly incrementing or decrementing?
- Did you accidentally put a semicolon directly after
fororwhile? - For nested loops, are you using different variable names for inner and outer loops?
Practice Problems (Loops & Patterns)
- Print all even numbers between 1 and 100 using a
forloop. - Use a
whileloop to read integers until the user enters 0, then print the sum. - Write a
do-whilebased menu: 1. Square, 2. Cube, 0. Exit. - Print a multiplication table for a given number (e.g., 7 × 1 to 7 × 10).
- Create a star pattern that prints a pyramid shape.
- Use loops to simulate 10 voltage readings and show only those outside the allowed range.
Suggested Featured Image Prompt
Use this prompt in your image generation tool for the thumbnail:
“Flat modern 16:9 illustration on a light background. Three flow diagrams are shown side by side: one labeled ‘for loop’, one labeled ‘while loop’ and one labeled ‘do-while loop’. Each diagram has arrows showing: ‘initialize → check condition → body → update → repeat’, with the do-while diagram clearly showing ‘body’ before ‘condition’. Below the diagrams, a simple star pattern triangle is displayed as console output. On the right, a South Indian / Tamil technician character sits at a desk with a laptop showing C code with `for`, `while` and `do { } while();` highlighted. At the top, bold title text: ‘Loops in C’ and smaller subtitle: ‘for, while, do-while – Patterns & Practice | Tamil Technicians’. Clean vector style, minimal colors, educational, high quality.”
FAQ: Loops in C
1. Which loop should I learn first?
Start with the for loop. It is the most common in examples and pattern programs.
Once you are comfortable, move to while and do-while.
2. How do I avoid infinite loops?
Make sure your loop variable is initialized, your condition can eventually become false, and the update statement actually changes the variable correctly in each iteration.
3. Are nested loops slower?
Nested loops do more total work (e.g., an outer loop of 100 and inner of 100 means 10,000 iterations), so they naturally take more time. But for small sizes and learning, this is not a problem.
4. Can I mix if–else and loops together?
Yes. In real programs, you will almost always combine loops with if, else-if,
and switch–case to make decisions inside the loop.


