Loops in C (for, while, and do-while)
Loops are used to execute a block of code repeatedly until a specified condition becomes false. C provides three types of loops:
forloopwhileloopdo-whileloop
1. for Loop
The for loop is used when the number of iterations is known in advance.
Syntax
for (initialization; condition; update)
{
// statements
}
- Initialization: Executes only once before the loop starts.
- Condition: Checked before each iteration.
- Update: Executes after each iteration.
Example
#include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 5; i++)
{
printf("%d\n", i);
}
return 0;
}
Output
1
2
3
4
5
2. while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition)
{
// statements
}
Example
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
i++;
}
return 0;
}
Output
1
2
3
4
5
3. do-while Loop
The do-while loop executes the loop body at least once, even if the condition is false.
Syntax
do
{
// statements
} while (condition);
Example
#include <stdio.h>
int main()
{
int i = 1;
do
{
printf("%d\n", i);
i++;
} while (i <= 5);
return 0;
}
Output
1
2
3
4
5
Example: Sum of First 10 Natural Numbers Using for
#include <stdio.h>
int main()
{
int i, sum = 0;
for (i = 1; i <= 10; i++)
{
sum += i;
}
printf("Sum = %d", sum);
return 0;
}
Output
Sum = 55
Example: Multiplication Table Using while
#include <stdio.h>
int main()
{
int num = 5, i = 1;
while (i <= 10)
{
printf("%d x %d = %d\n", num, i, num * i);
i++;
}
return 0;
}
Output
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Example: Menu Using do-while
#include <stdio.h>
int main()
{
int choice;
do
{
printf("\nMenu\n");
printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
} while (choice != 3);
printf("Program Ended.");
return 0;
}
Difference Between for, while, and do-while
| Feature | for Loop | while Loop | do-while Loop |
|---|---|---|---|
| Condition Checked | Before execution | Before execution | After execution |
| Minimum Executions | 0 | 0 | 1 |
| Best Used When | Number of iterations is known | Number of iterations is unknown | Loop must execute at least once |
| Initialization & Update | Included in loop header | Written separately | Written separately |
Advantages of Loops
- Reduce code repetition.
- Make programs shorter and easier to read.
- Improve code maintenance.
- Automate repetitive tasks.
Summary
forloop: Best when the number of iterations is known.whileloop: Best when the loop depends on a condition and the number of iterations is not fixed.do-whileloop: Executes the loop body at least once before checking the condition.- Loops are essential for performing repetitive tasks efficiently in C programming.
Category: MCA
