Loops in C Programming
Types of Loops in C
There are three main types:
- for loop
- while loop
- do–while loop
for Loop
The for loop is used when the number of iterations is known in advance.
Syntax
for(initialization; condition; increment/decrement)
{
statements;
}
Flow
- Initialization executes once
- Condition is checked
- Loop body executes
- Increment/decrement happens
- Steps repeat until condition becomes false
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
while Loop
The while loop is used when the number of iterations is not known beforehand.
The loop continues as long as the 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;
}
do–while Loop
The do–while loop executes the body at least once, even if the condition is false.
This is called an exit-controlled loop.
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;
}
Difference Between while and do–while
| while Loop | do–while Loop |
| Condition checked before execution | Condition checked after execution |
| May execute zero times | Executes at least once |
| Entry-controlled loop | Exit-controlled loop |
Nested Loops
A loop inside another loop is called a nested loop.
Example
#include <stdio.h>
int main()
{
int i, j;
for(i = 1; i <= 3; i++)
{
for(j = 1; j <= 3; j++)
{
printf(“* “);
}
printf(“\n”);
}
return 0;
}
Output:
* * *
* * *
* * *
Loop Control Statements
break Statement
Used to exit the loop immediately.
for(i = 1; i <= 10; i++)
{
if(i == 5)
break;
printf(“%d”, i);
}
continue Statement
Used to skip the current iteration and move to the next.
for(i = 1; i <= 5; i++)
{
if(i == 3)
continue;
printf(“%d”, i);
}
Differences Between break, continue, and goto
| Feature | break | continue | goto |
| Purpose | Exits a loop or switch block |
Skips the current iteration | Transfers control to a label |
| Scope |
Nearest enclosing loop or switch | Nearest enclosing loop | Any labeled state- ment in the same function |
| Use Case | Terminating loops or switch | Skipping specific iterations | Exiting deeply nested loops |
| Readability | Generally safe and readable | Generally safe and readable | Can make code harder to read |
Important Points to Remember
Infinite loop occurs when condition never becomes false
Semicolon after loop condition can create errors
Use proper initialization and increment
for(;;) creates an infinite loop
Example:
for(;;)
{
printf(“Infinite Loop”);
}
Practice Programs
- Print Numbers from 1 to 10
for(int i = 1; i <= 10; i++)
printf(“%d “, i);
- Sum of First N Numbers
int n, i, sum = 0;
scanf(“%d”, &n);
for(i = 1; i <= n; i++)
sum = sum + i;
printf(“Sum = %d”, sum);
- Multiplication Table
int num, i;
scanf(“%d”, &num);
for(i = 1; i <= 10; i++)
printf(“%d x %d = %d\n”, num, i, num*i);