C is a programming language that remains widely used in many workplaces because it allows compact and efficient code. Among its features, “loops” appear in virtually every program. A loop is a mechanism that automatically executes a specific operation repeatedly. For example, it is used to display numbers from 1 to 10 or to repeatedly accept user input based on conditions.
Why are loops important?
Without loops, you would have to write the same code manually many times. This leads to low maintainability, becomes a breeding ground for bugs, and makes the entire program redundant. Therefore, C provides three basic loop constructs:
for loop: used when the number of iterations is clearly determined
while loop: used when you want to continue processing as long as a condition is met
do…while loop: used when you need to execute the body at least once
By choosing the appropriate loop construct, you can build programs that are more flexible and efficient.
What you’ll learn in this article
In this article, we will thoroughly explain how to use each C loop construct, their differences, practical code examples, and common pitfalls and cautions. We aim to provide clear explanations that are easy to understand even for those who have just started learning C, so you can read with confidence.
2. Basics and Usage of the for Loop
What is a for Loop?
In C, the for loop is the syntax best suited for processes with a predetermined number of iterations. For example, cases such as “display numbers from 1 to 100 one by one” or “repeat a process only 10 times” are simple and clear with a for loop.
Basic Syntax of the for Loop
for (initialization; condition; update) {
// code to execute each iteration
}
The meaning of each part is as follows:
Initialization expression: initializes the counter variable (e.g., int i = 0;)
Condition expression: the loop continues while this condition is true
Update expression: increments or decrements the counter each iteration (e.g., i++)
Example: Display Numbers from 1 to 10
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
printf("%d
", i);
}
return 0;
}
In this code, the variable i increments by one from 1 to 10, repeating 10 times and displaying each value with printf. It is an intuitive and highly readable example of a loop.
Benefits of Using a for Loop
If the number of iterations is known, the code becomes shorter
Initialization, condition, and update can be combined in one line, making it readable
Works well with arrays, making it suitable for processing elements sequentially
Caution: Beware of Infinite Loops
If the condition expression is always true, an infinite loop occurs, as shown below.
for (;;) {
// repeats infinitely
}
This form is used when you intentionally want an infinite loop, but usually you need to watch out for unintended infinite loops caused by a mistake in the condition.
Using break and continue
Inside a for loop, use break to exit the loop early, and continue to skip a specific iteration.
for (int i = 1; i <= 10; i++) {
if (i == 5) continue; // skip 5
if (i == 8) break; // exit loop when i becomes 8
printf("%d
", i);
}
The output will be “1‑4, 6, 7”.
3. while Loop Basics and Usage
What is a while Loop?
while is a construct that repeats processing while a condition holds. Unlike for, it is suitable when the number of repetitions is not known in advance, or when processing should continue based on user input or external data state.
For example, in a process that repeats until the user enters a correct value, a while loop is intuitive.
Basic Syntax of while Loop
while (condition) {
// code to be executed repeatedly
}
condition is true, the processing inside the block repeats.
If the condition is false from the start, note that the loop will not execute even once.
Example: Display Numbers from 1 to 10
#include <stdio.h>
int main() {
int i = 1;
while (i <= 10) {
printf("%d
", i);
i++;
}
return 0;
}
This code achieves almost the same behavior as a for loop using a while loop. The difference is that initialization (int i = 1;) and increment (i++) must be written outside the loop.
When while Loops Shine: Control by User Input
#include <stdio.h>
int main() {
int input = 0;
while (input != -1) {
printf("Please enter a number (enter -1 to quit):");
scanf("%d", &input);
}
printf("Exiting.\n");
return 0;
}
Thus, processing that continues looping until the user enters a specific value is intuitive with a while loop.
Caution: Prone to Infinite Loops
If there is no change in the condition expression of a while loop, it can unintentionally become an infinite loop. Below is a bad example.
int i = 1;
while (i <= 10) {
printf("%d
", i);
// Forgetting i++ leads to an infinite loop...
}
→ Make sure to change the variable’s state within the loop.
Using break and continue
Even in a while loop, you can use break and continue just like in a for loop.
int num = 0;
while (num < 10) {
num++;
if (num == 5) continue; // skip 5
if (num == 8) break; // exit at 8
printf("%d
", num);
}
The output will be “1‑4, 6, 7”.
4. Basics and Usage of do…while Statements
What is a do…while Statement?
do...while is, among the three loop constructs available in C, the only one with the characteristic of guaranteeing that the body executes at least once. In a regular while loop, if the initial condition evaluates to false, the body never runs, but in a do...while loop the body executes first, then the condition is evaluated. Therefore it is suitable for situations such as “want to accept user input at least once” or “need to read a file at least once”.
Basic Syntax of do…while
do {
// Code to be repeated
} while (condition);
※ Note: a semicolon (;) is required after while.
Example: Display Numbers from 1 to 10
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d
", i);
i++;
} while (i <= 10);
return 0;
}
This code displays the numbers 1 through 10 just like a for or while loop. However, in a do...while loop the body runs first and the condition is checked afterward.
Typical Use: Re-prompting User Input
#include <stdio.h>
int main() {
int number;
do {
printf("Please enter a number 10 or greater:");
scanf("%d", &number);
} while (number < 10);
printf("Thank you. Entered value: %d
", number);
return 0;
}
In this example, if the user enters a number less than 10, they are prompted to enter it again. do...while is ideal for scenarios where executing the body at least once is a prerequisite.
Advantages and Considerations of do…while
Advantages
The body is guaranteed to execute at least once
Suitable for waiting for input or initialization tasks
Considerations
Because the body runs first, an incorrectly set condition may cause the loop to execute unintentionally more than once
Although used less frequently than for or while loops, it can be very handy when used appropriately
Using break and continue
do...while even supports break and continue. They allow flexible loop control based on conditions or counts.
int i = 0;
do {
i++;
if (i == 3) continue; // skip 3
if (i > 5) break; // display up to 5
printf("%d
", i);
} while (i < 10);
The output will be “1, 2, 4, 5”.
5. Choosing between for, while, and do…while loops
Understanding the differences between each loop statement
C has three types of repetition constructs (for, while, do…while), and any of them can implement repeated processing. So why are multiple loop constructs provided? It’s because each has situations where it is most suitable and ease of use. Here we explain how to choose among the three loop statements in a way that’s easy for beginners to understand.
for loop: Use when the number of repetitions is known
for loop has initialization, termination condition, and increment/decrement all in one line, making it very clear.
for (int i = 0; i < 10; i++) {
// Process that repeats 10 times
}
When the number of repetitions is fixed, consider using a for loop first. It is especially strong for array traversal and counter control.
while loop: Use when you want to repeat as long as a condition is met
while loop is useful when the number of repetitions is not clear.
For example, in processes that depend on external information such as user input or sensor values, the flexibility of a while loop comes into play.
while (!terminationCondition) {
// Process that repeats while the condition is true
}
When you need to decide each iteration whether to continue, using a while loop feels natural.
do…while loop: Use when you need to execute at least once
do...while loop is used in situations where you want to execute the process once before evaluating the condition.
do {
// Must execute the first iteration
} while (condition);
For example, it is suitable for situations like “display a menu once, then ask the user whether to display it again”.
Quick reference table for choosing
Task
Suitable loop construct
Fixed-count repetition
for loop
When you want to continue as long as the condition is true
while loop
When you need to execute at least once
do…while loop
When array or indexed processing is needed
for loop (especially recommended)
When input serves as the termination condition
while loop or do…while loop
Is it okay to use any of them in practice?
Of course, the same processing can be implemented with a for loop or a while loop. However, it is important to choose the “appropriate construct” to improve code readability and maintainability. For example, if the number of repetitions is clear but you implement it with a while loop, the condition and counter may be scattered outside the loop, making it harder to follow.
Conversely, writing a process that repeatedly accepts user input with a for loop can make the intent of the code harder to understand.
Choosing the optimal loop leads to readable, low‑bug code
Instead of picking a loop construct based on “looks” or “habit”, selecting it appropriately according to the purpose of the processing leads to higher program quality.
6. Cautions for Loop Processing
Looping is convenient, but without care it can become a breeding ground for bugs
Loop processing is a fundamental building block in programming and a very convenient construct. However, it is also a point where design mistakes or improper coding of loops can easily lead to unexpected issues and bugs. Here, we explain the key cautions to keep in mind for handling loop processing safely and correctly in C.
How to Prevent Infinite Loops
One of the most common problems is a infinite loop. This refers to a situation where the loop’s termination condition is never satisfied, causing the process to run indefinitely. For example, the following code requires caution.
int i = 0;
while (i < 10) {
printf("%d\n", i);
// If i++ is omitted, the loop will continue indefinitely
}
In this case, forgetting to include i++ leaves the value of i unchanged, causing the condition to remain constantly true. Countermeasures:
Check not only the condition expression but also that the “increment expression” is functioning correctly
Be aware of whether the condition changes during the loop
Proper Use of the break Statement
break is a control statement used to forcefully exit a loop. While convenient, overusing it can make the code’s intent harder to understand.
while (1) {
int input;
scanf("%d", &input);
if (input == 0) break; // Exit loop when 0 is entered
}
Thus, writing while (1) as an infinite loop and using break under specific conditions is common. To maintain readability, adding appropriate comments and extracting the logic into functions are effective strategies.
Be Careful Not to Overuse the continue Statement
continue is a control statement that skips the remainder of the current loop iteration and proceeds to the next repetition.
When used appropriately, it can streamline the flow, but overusing it in code with complex conditional branches can make it harder to understand.
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue; // Skip even numbers
printf("%d\n", i); // Print only odd numbers
}
This is effective for simple use cases, but caution is needed when conditions increase or the nesting becomes deep.
Cautions with Nested Loops
Embedding additional loops within a loop, known as nested loops, is also a convenient and commonly used pattern.
However, excessively deep nesting can complicate the code and may lead to issues such as:
The intent of the processing becomes hard to read
Performance degrades (especially with triple loops or more)
Bugs caused by reusing variables
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("i=%d, j=%d\n", i, j);
}
}
This level of nesting is fine, but when it gets deeper, consider splitting the logic into separate functions and adding comments to clarify parts of the processing to improve readability.
Watch Out for Mistakes in Conditions and Boundary-Value Bugs
Mistakes with comparison operators such as “<” or “<=” in loop conditions are also a common source of off‑by‑one logic bugs.
// When you want to output 0 through 9
for (int i = 0; i <= 9; i++) // Correct
// ↓ If you mistakenly use <, it will only output 0 through 8
for (int i = 0; i < 9; i++) // Causes a bug
Since loop processing is highly sensitive to boundary values, always verify that the desired number of iterations and range are correctly specified.
7. Frequently Asked Questions (FAQ)
Q1. What is the difference between a for loop and a while loop?
A: Both are constructs for repeated execution, but they are typically distinguished by the following points:
for is fundamentally used when the number of iterations is known. Because the initialization, condition, and update can be written in a single line, it offers good readability.
while is suitable when you want to repeat as long as a condition holds. It is useful when the number of iterations is unknown or when repetition depends on a condition.
Example:
// for loop (repeat 10 times)
for (int i = 0; i < 10; i++) {
// processing
}
// while loop (repeat only while a specific condition is met)
while (condition) {
// processing
}
Q2. When should you use a do…while loop?
A:do...while is used when you need to execute the body at least once. For example, it fits cases where you always display a menu first and then continue processing based on the user’s selection.
int option;
do {
printf("1. Redisplay 2. Exit:");
scanf("%d", &option);
} while (option == 1);
Thus, in logic where the processing is assumed to run unconditionally from the first iteration, a do...while is appropriate.
Q3. How can you prevent an infinite loop?
A: An infinite loop is a situation where the loop’s termination condition is never satisfied, causing the program to run indefinitely. In C, the following causes are common:
Not updating the counter variable
Design mistakes that make the condition always true
The loop’s termination condition is not set correctly
As countermeasures:
Check inside for and while loops that variables are changing
Review whether the termination condition is correctly
During debugging, it can be effective to incorporate a safety mechanism that forces termination after a certain number of iterations (e.g., a counter limit)
Q4. What is the difference between break and continue?
A: Both are statements used for loop control, but they behave differently:
breakterminates the loop itself. It is often used when you want to exit the loop early once a condition is met.
continueskips the rest of the current iteration and proceeds to the next loop iteration.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // skip 3
if (i == 5) break; // exit loop at 5
printf("%d\n", i);
}
The output will be “1, 2, 4”.
Q5. What loop construct should I use when I’m unsure?
A: Consider the following to make a choice easier:
Situation
Recommended construct
When the number of iterations is known
for
When you want to continue as long as a condition holds
while
When you need to execute at least once
do…while
Also, considering readability and your team’s coding style, it’s best to choose the construct that clearly conveys the intent at a glance.
8. Summary
In this article, we explained the three loop constructs—for loops, while loops, and do…while loops—that are the fundamentals of iteration in C, covering how to use each and the points for choosing among them. Iteration is one of the most basic yet powerful mechanisms in programming. It appears in every scenario, from automating tasks and repeating input to looping based on conditions.
Review of Each Loop Construct
for loops: Ideal when the number of iterations is known. You can write the counter variable and loop condition on a single line, which enhances readability.
while loops: Used when you want to continue processing as long as a condition holds. Allows flexible handling based on external input or state changes.
do…while loops: Guarantees at least one execution, making it handy for cases where the initial processing must run.
Precautions When Working with Loop Processing
Watch out for infinite loops and mistakes in condition expressions
Understand correctly how break/continue work and their effects
Be mindful of code structure to avoid overly deep nesting
Choose syntax that makes the intent of the code easy to read
Finally: Tips for Learning
The most effective way to master iteration is by writing code hands‑on. Start with simple count‑up or conditional loops, then gradually tackle more advanced topics like user input and nested loops. Iteration is one of the pillars that supports your programming skills. Use this article as a reference, and try writing and running code on your own.