Loops in Programming: For, While and Do-While with Examples
A loop in programming is a control structure that repeats a block of code while a specified condition remains true. The three main types are for, while, and do-while. Use a for loop when the count is fixed, a while loop when it is condition-driven, and a do-while loop when the code must run at least once.
Key Takeaways
- A loop repeats code until a condition fails, saving you from writing duplicate lines.
- Use a for loop when the number of iterations is known in advance.
- Use a while loop when you repeat based on a condition, not a fixed count.
- A do-while loop always runs at least once because it checks the condition after executing the body.
- Forgetting to update the counter variable is the most common cause of an infinite loop.
What Is a Loop in Programming and Why Does Every Programmer Need One?
Imagine you are building a student grade calculator for a class of 60 students at an Indian university. Without loops, you would copy-paste the same calculation block 60 times. That is not programming, that is typing. Loops solve this by letting you write the logic once and letting the computer handle the repetition. Understanding what is a loop in programming is one of the first skills covered in the GATE CS syllabus and in virtually every B.Tech Computer Science curriculum across India.
According to the TIOBE Index (July 2025), C remains one of the top three most-used programming languages globally, and loop constructs are foundational to everything from embedded systems to operating system kernels written in C. If you are aiming at a tech career, understanding iteration is non-negotiable.
Loops also introduce you to some of the most critical programming concepts: the counter variable (which tracks how many times you have looped), the break statement (which exits a loop early), the continue statement (which skips the current iteration and moves to the next), and nested loops (loops inside loops, used for things like printing multiplication tables or processing 2D arrays).
The 2024 Stack Overflow Developer Survey found that over 60% of developers cite foundational programming concepts like loops and conditionals as the skills they use every single day, more than any framework or library. Getting loops right is not a beginner exercise; it is a career-long habit. You can explore more foundational skills through 3.0 University’s learning resources.
For vs While vs Do-While: Understanding What Is a Loop in Programming Across All Three Types
All three loop types repeat code. The difference is in when they check the condition and how much control you have over the iteration count. Here is the same task written three ways.
Printing numbers 1 to 5: three approaches
For loop approach: You know exactly how many times to run it, so the for loop is the cleanest choice.
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
The for loop packs the initialisation (int i = 1), the condition (i <= 5), and the increment (i++) into one line. It is compact and readable when the iteration count is fixed.
While loop approach: The while loop checks its condition before executing the body. If the condition is false from the start, the body never runs.
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
This is an entry-condition loop. It is ideal when you do not know upfront how many iterations you will need, like reading user input until someone types “quit”.
Do-while loop approach: The do-while checks its condition after executing the body. That makes it an exit-condition loop, and it is guaranteed to run at least once.
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
All three print the same output for this specific case. But change the starting value to i = 10 and the while loop prints nothing, while the do-while still prints 10 once before checking the condition.
Quick comparison table: for vs while vs do-while in C programming
| Loop Type | Condition Checked | Minimum Executions | Best Use Case |
|---|---|---|---|
| for | Before each iteration | 0 | Known iteration count (arrays, tables, fixed ranges) |
| while | Before each iteration | 0 | Condition-driven repetition (reading input, polling) |
| do-while | After each iteration | 1 (always) | Must run at least once (menus, input validation) |
Infinite loops and off-by-one errors in C
An infinite loop happens when the loop’s condition never becomes false. The classic cause in C is forgetting to increment the counter variable. This loop runs forever:
int i = 0;
while (i < 5) {
printf("%d\n", i);
// forgot i++;
}
Your program freezes, your CPU spikes, and you have a problem. Always double-check that something inside the loop actually moves you toward the exit condition.
The off-by-one error is equally sneaky. Using i < 5 runs the loop for values 0, 1, 2, 3, 4. Using i <= 5 runs it for 0 through 5. One extra iteration can corrupt array access or produce wrong totals. According to a 2022 study published in IEEE Transactions on Software Engineering, off-by-one errors account for roughly 25% of boundary-related bugs in student-written code. Pay attention to whether your condition uses < or <=.
How nested loops work in C programming
A nested loop is simply a loop inside another loop. The classic example is printing a multiplication table. The outer loop controls the row, the inner loop controls the column. Every time the outer loop runs once, the inner loop completes all its iterations. For a 10×10 table, that is 100 total iterations from just two loops.
Nested loops are powerful but expensive. Two nested loops that each run n times produce O(n squared) time complexity. That matters a lot when you start working on cybersecurity projects involving large datasets or packet analysis.
Do-While Loop in C: A Working Example with Output
The do-while loop is especially useful for menu-driven programs, which are common in C programming assignments across Indian engineering colleges. The menu needs to appear at least once, and the user should be able to keep choosing options until they select “Exit”. This is a textbook example of what is a loop in programming applied to a real scenario.
#include <stdio.h>
int main() {
int choice;
do {
printf("\n--- Student Menu ---\n");
printf("1. View Marks\n");
printf("2. View Attendance\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Marks: 85/100\n");
break;
case 2:
printf("Attendance: 92%%\n");
break;
case 3:
printf("Goodbye!\n");
break;
default:
printf("Invalid choice. Try again.\n");
}
} while (choice != 3);
return 0;
}
Sample output when user enters 1, then 3:
--- Student Menu ---
1. View Marks
2. View Attendance
3. Exit
Enter your choice: 1
Marks: 85/100
--- Student Menu ---
1. View Marks
2. View Attendance
3. Exit
Enter your choice: 3
Goodbye!
Notice how the menu always appears before the condition choice != 3 is ever checked. That is the defining behaviour of a do-while loop in C programming. You could not replicate this naturally with a while loop without duplicating the menu code outside the loop.
The break statement inside the switch exits the switch block, not the loop. The loop itself only ends when the while condition (choice != 3) evaluates to false. This is a distinction that trips up many beginners in their first semester of C programming.
If you are preparing for placements or building your portfolio, understanding these control structures deeply will serve you far better than memorising syntax. Platforms offering structured learning paths, like those listed in guides on career paths after 12th grade, consistently highlight C programming fundamentals as a gateway skill.
Students using tools like the GitHub Education Program get free access to development environments where you can compile and test exactly this kind of C code in the cloud, with no local setup required.
Loops are also foundational to understanding how blockchain developers use programming languages for iterating over transaction blocks, validating chains, and processing smart contract logic. The concept scales far beyond beginner exercises.
If you are serious about building a career in tech, consider enrolling in a structured certification programme. 3.0 University’s online courses in Cybersecurity, Ethical Hacking, AI, Blockchain and Web3 are built for students, working professionals, and career switchers who want practical, industry-ready skills, not just theory.
Frequently Asked Questions
What is a loop in programming?
A loop in programming is a control structure that repeats a block of code while a condition remains true. It saves you from writing duplicate instructions and makes your code shorter, cleaner, and easier to maintain. The three main types are for, while, and do-while, each suited to different situations depending on whether the iteration count is known in advance.
What is the difference between while and do-while loops?
A while loop checks its condition before running the body, so if the condition is false from the start, the body never executes. A do-while loop checks the condition after running the body, guaranteeing at least one execution. Use do-while when the code must run at least once, like showing a menu or collecting the first piece of user input.
When should I use a for loop?
Use a for loop when you know exactly how many times the code should repeat before the loop starts. It keeps the initialisation, condition, and increment all in one place, making the code easier to read. Common examples include iterating over arrays, printing tables, and counting from one number to another with a fixed step.
What is an infinite loop and how do I avoid it?
An infinite loop runs forever because its exit condition never becomes false. The most common cause is forgetting to update the counter variable inside the loop. To avoid it, always make sure something inside the loop changes the variable being tested in the condition. You can also use a break statement to force an exit when a specific event occurs.
How does a do-while loop work in C programming?
In C, a do-while loop executes the body first, then evaluates the condition at the bottom using the syntax do { ... } while (condition);. Because the check happens after the body, the code runs at least once regardless of the condition’s initial value. It is commonly used in menu-driven programs where you need to display options before asking the user to choose.
What happens when a loop condition is never false?
When a loop condition never becomes false, the loop runs indefinitely, creating an infinite loop. The program stops responding, memory usage can climb, and the CPU load spikes. You can prevent this by ensuring the loop variable is updated inside the body, or by adding a break statement that triggers when a maximum iteration count or a specific event is reached.
Can you nest a for loop inside a while loop in C?
Yes. In C programming, any loop type can be nested inside any other loop type. A for loop inside a while loop is perfectly valid. The outer while loop controls the broader condition, and the inner for loop handles a fixed number of sub-iterations each time the outer loop runs. Just be mindful of time complexity: two nested loops each running n times produce O(n squared) performance.
Last updated: August 2026. Reviewed by the 3University editorial team.


