Published: 16 Apr 2025 | Reading Time: 12 min read
Try creating a program in C that prints numbers one to hundred. Would you write a hundred lines of code? Right? Not at all. That's where loops in C come into play. Loops are one of the most fundamental programming concepts, enabling you to run a block of code repeatedly until the specified condition is met. There are three types of loops used in the C language. What if you want to skip specific iterations or need to end a loop early? This is where loop control statements like goto, continue, and break are necessary.
You will learn everything a C programmer should know about loops in C and loop control statements in this detailed guide.
In C, loops are control structures that enable you to repeatedly run a piece of code until a predetermined condition is satisfied. By automating repetitive processes improves the efficiency and maintainability of your code. Loops are necessary for tasks like processing user input, iterating across arrays, and resolving issues that call for repetitive computations.
A code block is continually executed if a given condition is true in a loop. After the condition is changed to false, the loop ends, and the program moves on to the following statement.
Looping is one of the fundamental concepts in programming that allows a set of instructions to be executed repeatedly until a specific condition is met. Here are some key advantages of using loops:
1. Saves Time and Effort
Loops eliminate the need to write repetitive code. Instead of repeating the same instructions multiple times, a loop can execute them automatically, saving both time and effort for the programmer.
2. Improves Code Efficiency
With loops, programs can handle large volumes of data and perform tasks more efficiently. This makes your code cleaner, more compact, and easier to manage.
3. Enhances Flexibility and Scalability
Loops allow your program to adapt to changes in data size. Whether you're processing 10 items or 10,000, loops make your code scalable without rewriting logic.
4. Supports Automation and Reusability
Loops enable automation of repetitive tasks such as calculations, data processing, and user input validation. This makes your code more reusable and reduces the chances of manual errors.
5. Facilitates Better Logic Implementation
Many algorithms rely on iteration to function correctly. Loops are essential in implementing logic for searching, sorting, traversing data structures, and more.
In C programming, loops are essential constructs that allow the execution of a block of code multiple times based on a specified condition. This repetition facilitates tasks such as iterating over data structures, performing calculations, and automating repetitive operations. The primary types of loops in C are:
1. Entry-Controlled Loops
2. Exit-Controlled Loop
Let's delve into each type, clearly explaining their algorithms, corresponding C code, detailed explanations, and expected outputs.
In entry-controlled loops, the loop's condition is evaluated before executing the loop's body. The loop body is not executed if the condition is initially evaluated as false.
The for loop is a control structure that allows code to be executed repeatedly for a known number of iterations. As long as the condition is true, the loop runs. It has three parts: initialization, condition, and update.
for (initialization; condition; update) {
// Code to be executed
}
#include <stdio.h>
int main() {
// Using for loop to print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
return 0;
}
1 2 3 4 5
Here's a simple example program in C to calculate the sum of the first 30 natural numbers using a for loop.
#include <stdio.h>
int main() {
int sum = 0;
// Loop from 1 to 30
for (int i = 1; i <= 30; i++) {
sum += i; // Add current number to sum
}
// Print the result
printf("The sum of the first 30 natural numbers is: %d\n", sum);
return 0;
}
The sum of the first 30 natural numbers is: 465
The while loop is used when the number of iterations is not known in advance. It first checks the condition, and if it's true, it executes the loop body. The loop continues until the condition becomes false. It is also called a pre-tested loop.
while (condition) {
// Code to be executed
}
#include <stdio.h>
int main() {
int i = 0; // Initialization
while (i <= 5) { // Condition Evaluation
printf("%d ", i);
i++; // Update
}
return 0;
}
0 1 2 3 4 5
#include <stdio.h>
int main() {
// Infinite loop using while
while (1) {
printf("This is an infinite loop!\n");
}
return 0;
}
In exit-controlled loops, the loop's body is executed first, and the condition is evaluated after the execution. This guarantees that the loop body executes at least once, regardless of the condition's initial state.
The do-while loop guarantees that the body executes at least once before checking the condition. It is useful when the loop must execute at least once, regardless of the condition. It is also called post-tested loop.
do {
// Code to be executed
} while (condition);
#include <stdio.h>
int main() {
int i = 1; // Initialization
do {
printf("%d ", i);
i++; // Update
} while (i <= 5); // Condition Evaluation
return 0;
}
1. Initialization
2. do Block Execution
3. Condition Evaluation (After Block)
4. Loop Repeats Until
1 2 3 4 5
Here are the key differences between for, while and do-while loops:
| Aspect | for Loop | while Loop | do-while Loop |
|---|---|---|---|
| Definition | A loop that integrates initialization, condition checking, and updating within a single statement. Ideal when the number of iterations is predetermined. | A loop that evaluates a condition before each iteration and continues to execute as long as the condition remains true. | A loop that executes the code block once before evaluating the condition, ensuring at least one execution regardless of the condition. |
| Syntax | for (initialization; condition; update) { /* code */ } | while (condition) { /* code */ } | do { /* code */ } while (condition); |
| Initialization | Performed once at the start within the loop statement. | Must be done explicitly before entering the loop. | Must be done explicitly before entering the loop. |
| Condition Evaluation | Checked before each iteration; if false initially, the loop body may not execute at all. | Checked before each iteration; if false initially, the loop body does not execute. | Checked after the loop body executes; thus, the loop body always executes at least once. |
| Update | Typically included within the loop statement and executed after each iteration. | Must be handled explicitly within the loop body. | Must be handled explicitly within the loop body. |
| Entry/Exit Control | Entry-controlled loop (condition is evaluated before entering the loop body). | Entry-controlled loop (condition is evaluated before entering the loop body). | Exit-controlled loop (condition is evaluated after the loop body executes). |
| Loop Body Execution | May not execute at all if the condition is false initially. | May not execute at all if the condition is false initially. | Executes at least once, regardless of the initial condition. |
| Use Cases | Suitable when the number of iterations is known beforehand, such as iterating over arrays or fixed ranges. Offers a compact and structured way to write loops, encapsulating all loop control elements in a single line and enhancing readability for simple loops. | Ideal when the number of iterations isn't predetermined and depends on dynamic conditions. | Useful when the loop must execute at least once, such as in menu-driven programs requiring user interaction. |
| Readability | It offers a compact and structured way to write loops, encapsulating all loop control elements in a single line and enhancing readability for simple loops. | Provides flexibility but may require careful management of loop control variables, potentially affecting readability. | Ensures at least one execution, which can be beneficial but might lead to unintended behavior if not handled properly. |
| Common Pitfalls | Overlooking the update statement can lead to infinite loops; modifying loop control variables inside the loop body can cause unexpected behavior. | Forgetting to update the loop control variable or incorrect condition evaluation can result in infinite loops. | Misunderstanding that the loop executes at least once can lead to errors if the initial condition is not intended without a condition check. Slightly less efficient in scenarios where the loop body should not execute if the condition is false initially, due to mandatory first execution. |
| Performance | Generally efficient for scenarios with a known number of iterations; minimal overhead due to compact structure. | It can be efficient, but may introduce overhead if the loop control variables are not managed properly. | Slightly less efficient in scenarios where the loop body should not execute if the condition is false initially, due to mandatory first execution. |
| Example | for (int i = 0; i < 5; i++) { printf("%d ", i); } | int i = 0; while (i < 5) { printf("%d ", i); i++; } | int i = 0; do { printf("%d ", i); i++; } while (i < 5); |
A loop becomes an infinite loop when its condition never evaluates to false. An infinite loop is a loop that continues to execute indefinitely because it lacks a terminating condition, the termination condition is never satisfied, or the loop is directed to start over from the beginning.
An infinite loop runs endlessly until it is forcefully stopped. Below is an example of creating an infinite loop using the for statement.
#include <stdio.h>
int main() {
// Infinite for loop
for (;;) {
printf("This is an infinite loop!\n");
}
return 0;
}
This is an infinite loop!
In C programming, a do-while loop can be intentionally crafted to run indefinitely by setting its condition to always evaluate as true. Below is an example explaining this concept:
#include <stdio.h>
int main() {
int count = 1; // Initialize a counter variable
do {
printf("Iteration: %d\n", count);
count++;
// To prevent the loop from running indefinitely during demonstration,
// we'll break out of the loop after 10 iterations.
if (count > 10) {
break;
}
} while (1); // The condition is always true, creating an infinite loop
printf("Exited the loop after 10 iterations.\n");
return 0;
}
Note: In practical scenarios, infinite loops are generally avoided unless there's a specific requirement, such as in embedded systems or server applications, where the program needs to run continuously. Always ensure there's a mechanism to exit the loop to prevent the program from becoming unresponsive.
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Iteration: 6
Iteration: 7
Iteration: 8
Iteration: 9
Iteration: 10
Exited the loop after 10 iterations.
Using loops efficiently can make your C programs more effective and easier to read. Here are some practical tips to follow while working with loops in C:
1. Choose the Right Loop Type
If you are aware of the total number of iterations, utilize a for loop. Use a while loop when the condition depends on something that changes during execution. Use a do-while loop when the loop must run at least once.
2. Avoid Infinite Loops (Unless Intentional)
Always make sure your loop condition will eventually become false. Update the loop control variable properly to prevent accidental infinite loops.
3. Keep Loop Logic Simple
Don't stuff excess logic within a single loop. If the loop body becomes complex, break it into smaller functions for better readability and maintenance.
4. Avoid Repeating Calculations in the Loop Condition
If you're using a value that doesn't change during the loop, compute it once before the loop starts. This improves performance and readability.
5. Initialize Loop Variables Properly
Always assign a starting value to loop variables. Uninitialized variables can lead to unexpected behavior.
6. Use Descriptive Variable Names
While short names like i or j are fine for small loops, prefer meaningful names in larger or nested loops to improve code clarity.
7. Use break and continue Carefully
These statements can help control loop flow, but overusing them may make your code harder to follow. Use them only when it genuinely makes the code cleaner.
8. Avoid Off-by-One Errors
Carefully plan your loop boundaries. Check whether your loop should use <, <=, or other conditions to avoid skipping or repeating iterations.
A loop nested inside another loop is known as a nested loop in C programming. This is beneficial for patterns, multi-dimensional arrays, and complicated logic structures because it enables you to repeat a set of instructions inside another repeated set.
You can nest any kind of loop (for, while, or do-while) inside each other. Here are the common types:
A nested for loop is when you place one for loop inside the body of another. It's commonly used to handle rows and columns, grids, patterns, or 2D arrays.
for (initialization; condition; update) {
for (initialization; condition; update) {
// Inner loop code
}
// Code after inner loop
}
Below is a simple example provided to understand how nested for loops work.
#include <stdio.h>
int main() {
for (int i = 1; i <= 4; i++) { // Outer loop for rows
for (int j = 1; j <= 4; j++) { // Inner loop for columns
printf("%d ", j);
}
printf("\n"); // Newline after each row
}
return 0;
}
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
Nested while loops in C are loops placed inside another while loop, allowing repeated execution of inner code for each outer loop iteration commonly used for patterns, tables, and multi-dimensional data.
while (condition1) {
// Outer loop body
while (condition2) {
// Inner loop body
}
}
#include <stdio.h>
int main() {
int i = 1;
while (i <= 3) { // Outer loop for rows
int j = 1;
while (j <= 3) { // Inner loop for columns
printf("* ");
j++;
}
printf("\n"); // Move to next line after each row
i++;
}
return 0;
}
* * *
* * *
* * *
A nested do-while loop means placing one do-while loop inside another do-while loop. This allows you to perform a set of actions repeatedly within another repeated set of actions.
do {
// Outer loop body
do {
// Inner loop body
} while (condition2);
} while (condition1);
Here is a simple program using nested do-while loops.
#include <stdio.h>
int main() {
int i = 1;
do {
int j = 1;
do {
printf("* ");
j++;
} while (j <= 3); // Inner loop
printf("\n");
i++;
} while (i <= 2); // Outer loop
return 0;
}
* * *
* * *
Loop control statements in C modify the normal flow of loops. They provide additional control over how loops execute, allowing you to exit loops earlier, skip iterations, or jump to specific parts of your program. These statements are essential for writing efficient and flexible code.
In this section, you will explore the three main loop control statements in C:
The break is the primary loop statement in C that terminates a loop immediately, regardless of its condition. When the break statement is encountered inside a loop, the loop is exited, and the program continues with the following statement after the loop.
break;
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
printf("%d ", i);
}
printf("\nLoop ended.\n");
return 0;
}
1 2 3 4
Loop ended.
To go to the next iteration of a loop and bypass the current one, the continue statement is used. When the continue statement is encountered, the remaining code in the loop body is skipped, and the loop proceeds with the next iteration.
continue;
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the iteration when i is 3
}
printf("%d ", i);
}
printf("\nLoop ended.\n");
return 0;
}
1 2 4 5
Loop ended.
The goto statement is used to jump to a specific part of the program, identified by a label. It allows you to transfer control to another part of the code, bypassing the normal flow of execution.
goto label;
...
label:
#include <stdio.h>
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
goto end; // Jump to the label 'end'
}
printf("i = %d, j = %d\n", i, j);
}
}
end:
printf("Loop ended.\n");
return 0;
}
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
Loop ended.
These three statements control the execution flow in loops and conditional statements, but serve different purposes.
| Feature | break | continue | goto |
|---|---|---|---|
| Purpose | Exits the loop or switch statement immediately. | Skips the current iteration and moves to the next iteration. | Jumps to a labeled statement anywhere in the program. |
| Usage | Used in loops (for, while, do-while) and switch statements. | Used in loops (for, while, do-while). | Used anywhere in the program with a label. |
| Effect on Loop | Terminates the loop completely. | Skips the rest of the current iteration and continues with the next cycle. | Can move execution to any labeled part of the program. |
| Readability | Improves clarity by allowing early exit from loops. | Helps in skipping unwanted iterations cleanly. | Reduces readability and maintainability, often leading to "spaghetti code." |
| Common Use Cases | Exiting a loop when a condition is met (e.g., breaking out of a search loop when an item is found). | Skipping specific cases in a loop (e.g., skipping even numbers in an iteration). | Rarely recommended; used for error handling in legacy code. |
In programming, loop control statements have special instructions that aid in controlling the way loops function. Here are a few of their main advantages:
1. Preventing Unnecessary Repetition
They allow you to break out of a loop early when certain conditions are satisfied, saving the program time by avoiding repetitive operations.
2. Handling Errors Simply
These statements can assist the program in reacting effectively to an unexpected event during a loop, such as skipping over bad data without crashing.
3. Enhancing Code Clarity
These statements make your code easier to read and understand by stating exactly when and how loops should stop or stages should be skipped.
4. Managing Resources Wisely
They help ensure that loops don't run longer than necessary, which is important for saving memory and processing power.
5. The Application of Complex Logic Simply
These statements offer an easy way of managing the flow, simplifying implementation for tasks requiring complex looping patterns.
When using loop control statements like goto, break, and continue, it's important to be aware of common pitfalls that can lead to difficulty reading, maintaining, or debugging code. Here are some mistakes to watch out for:
1. Overusing goto
Excessive use of goto can make code hard to follow and maintain. It's generally advisable to use structured control flow constructs instead.
2. Creating Infinite Loops
Failing to define proper termination conditions can result in loops that never end. Always ensure that loops have well-defined exit criteria to prevent endless execution.
3. Misusing continue
Using continue improperly can skip essential code within a loop iteration. Be cautious to ensure that important operations aren't inadvertently bypassed.
Here are three practice problems focusing on loops that are commonly encountered in technical interviews:
Write a program that reads a positive integer and calculates the sum of its digits.
#include <stdio.h>
int main() {
int n, sum = 0, remainder;
// Prompt user for input
printf("Enter a positive integer: ");
scanf("%d", &n);
// Calculate sum of digits
while (n != 0) {
remainder = n % 10; // Extract the last digit
sum += remainder; // Add it to the sum
n /= 10; // Remove the last digit
}
// Display the result
printf("Sum of digits: %d\n", sum);
return 0;
}
The program repeatedly extracts the last digit of the number using the modulus operator (n % 10) and adds it to a running total (sum). It then removes the last digit by performing integer division by 10 (n /= 10). This process continues until all digits have been processed.
Enter a positive integer: 935
Sum of digits: 17
Write a program that reads an integer and outputs its reverse.
#include <stdio.h>
int main() {
int n, reversed = 0, remainder;
// Prompt user for input
printf("Enter an integer: ");
scanf("%d", &n);
// Reverse the number
while (n != 0) {
remainder = n % 10; // Extract the last digit
reversed = reversed * 10 + remainder; // Append it to the reversed number
n /= 10; // Remove the last digit
}
// Display the result
printf("Reversed number: %d\n", reversed);
return 0;
}
The program constructs the reversed number by extracting the last digit of the original number and appending it to the reversed number. This is achieved by multiplying the current reversed number by 10 and adding the extracted digit. The original number is then reduced by removing its last digit. This process repeats until the original number becomes zero.
Enter an integer: 12345
Reversed number: 54321
Write a program that prints the first n terms of the Fibonacci sequence.
#include <stdio.h>
int main() {
int n, t1 = 0, t2 = 1, nextTerm;
// Prompt user for input
printf("Enter the number of terms: ");
scanf("%d", &n);
// Display the first two terms
printf("Fibonacci Series: %d, %d", t1, t2);
// Calculate and display the remaining terms
for (int i = 3; i <= n; ++i) {
nextTerm = t1 + t2;
printf(", %d", nextTerm);
t1 = t2;
t2 = nextTerm;
}
printf("\n");
return 0;
}
The program initializes the first two terms of the Fibonacci sequence as 0 (t1) and 1 (t2). It then prints these two terms. For the subsequent terms, it calculates each new term by summing the previous two terms (nextTerm = t1 + t2), prints the new term, and updates the previous terms (t1 = t2; t2 = nextTerm). This loop continues until the desired number of terms is generated.
Enter the number of terms: 5
Fibonacci Series: 0, 1, 1, 2, 3
Loops and loop control statements are crucial components in C programming. They enable you to handle repetitive tasks more efficiently and manage the flow of your programs. You can write more efficient, readable, and flexible code by mastering the concept of loops in C programming and the loop control statements. These tools will support you in achieving your objectives, whether you are developing simple applications or intricate algorithms.
Therefore, when you need to repeat a section of code or manipulate the progression of your loops, consider the significance of loops in C and utilize them thoughtfully. With the information provided in this guide, you now understand loops and loop control statements in C, including their syntax and various applications. These principles will enhance your programming skills, whether coding a basic application or addressing complex algorithms.
The three types of loops in C are:
The three loop structures in C are:
A finite loop runs for a limited number of iterations and terminates when a predefined condition is met.
A fixed loop runs for a specific number of iterations, typically using a for loop with a predetermined number of repetitions.
The key difference is that the while loop checks the condition before executing the loop body, whereas the do-while loop executes the loop body at least once before checking the condition.
You can exit a loop in C using the break statement, which immediately terminates the loop and moves to the next statement after it.
An infinite loop never terminates because the loop condition never becomes false. It can be avoided by ensuring proper loop exit conditions, using break statements, or implementing correct loop updates.
Understanding the Selection Sort Algorithm - A comprehensive guide to the Selection Sort Algorithm covering concepts, working steps, and hands-on coding examples. (04 Jan 2026, 8 min read)
Mastering Insertion Sort in C: Code, Logic, and Applications - Understand insertion sort in C with easy-to-follow logic, code examples, and practical tips. (02 Jan 2026, 6 min read)
Complete Guide on String Functions in C - Learn essential string functions in C with syntax, examples, memory rules, and safe practices. (02 Jan 2026, 5 min read)
Quick Sort Algorithm Explained: Steps, Code Examples and Use Cases - Learn the Quick Sort Algorithm with clear steps, partition logic, Python & C++ code examples. (02 Jan 2026, 6 min read)
Switch Statement in C: Syntax, Flowchart & Sample Programs - Learn how to use the switch statement in C programming with simple syntax, real-life examples, and use cases. (02 Jan 2026, 6 min read)
The Ultimate Guide to Binary Search Algorithm in C - Learn the Binary Search Algorithm with steps, examples, and efficiency insights. (02 Jan 2026, 8 min read)
Source: NxtWave - https://www.ccbp.in/blog/articles/loops-in-c