Loops are fundamental constructs in programming languages, enabling the repetition of a code block of code until a certain condition is met or for a specified number of iterations. In the C programming language, loops play a pivotal role in executing tasks efficiently and are essential for implementing iterative solutions.
Table of Contents
There are three types of loops in C – the for
loop, the while
loop, and the do-while
loop. Each serves a specific purpose and offers distinct advantages depending on the situation.
for Loop in C
The for
loop is widely used when the number of iterations is known beforehand. Its syntax consists of three parts enclosed in parentheses: initialization, condition, and increment/decrement
Syntax
for (initialization; condition; increment/decrement) {
// Code to be executed repeatedly
}
for Loop Example in C
Let’s see an example of a for loop in c Programming
#include <stdio.h>
void main()
{
for (int i = 1; i <= 5; i++)
{
printf("%d ", i);
}
}
Output
The above C program example uses a for loop to print numbers from 1 to 5.
while Loop in C
The while loop is used when the number of iterations is not explicitly known in advance, depending on the condition of whether to continue executing the loop or terminate the loop.
Syntax
while(condition)
{
//code to be executed
}
while loop Example in C
Let’s see an example of a while loop in c Programming
#include <stdio.h>
void main()
{
int i = 1;
while (i <= 5)
{
printf("%d ", i);
i++;
}
}
Output
The above C program uses a while loop to print numbers from 1 to 5.
do-while Loop in C
The do-while loop is similar to a while loop but the do-while loop guarantees that the loop body is executed at least once before checking the condition for continuation.
Syntax
do
{
//code to be executed
}while(condition);
do-while Loop Example in C
Let’s see an example of a do-while loop in c Programming.
#include <stdio.h>
void main()
{
int i = 1;
do
{
printf("%d ", i);
i++;
} while (i <= 5);
}
Output
The above C program uses a do-while loop to print numbers from 1 to 5.
Common Use Cases of Loops
- Iterating Through Arrays – Loops are extensively used to traverse through arrays.
- Menu-Driven Programs- Loops allow the creation of user-friendly menu-driven programs, where users can interactively choose different options until they decide to exit.
- Performing Calculations- Loops are crucial for performing mathematical calculations, simulation, or generating sequences.
Best Practices for Using Loops in C
- Ensure that the loop termination condition is properly defined to prevent infinite looping .
- Initialize loop control variable appropriately to avoid unexpected behaviour.
- Keep the loop body concise and focused to enhance readability and maintainability.
Happy Coding
4 thoughts on “Loops in C”