Chapter 05 · C Programming Series
For Loop in C
A for loop in C is a control flow statement that allows code to be executed repeatedly based on a condition. The loop is particularly useful for iterating a fixed number of times or over a range of values.
What is for loop ?
syntax of for loop
The syntax of a for loop in C is as follows:
for (initialization; condition; increment) {
// Code to be executed repeatedly
}
Components
- Initialization : This is executed only once, at the beginning of the loop. It usually initializes one or more loop counters.
- Condition : This expression is evaluated before each iteration of the loop. If the condition is true, the loop body is executed. If it is false, the loop terminates.
- Increment : This is executed after each iteration of the loop body. It usually increments or decrements the loop counter.
Example
Here is a simple example of a for loop in C that prints numbers from 1 to 10 :
C Code
#include <stdio.h>
main()
{
int i;
for (i = 1; i <= 10; i++)
{
printf("%d ", i);
}
}
Output
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
- Explanation of the Example :
- Initialization : int i = 1; initializes the loop counter i to 1.
- Condition : i <= 10; checks if i is less than or equal to 10. If true, the loop body executes.
- Increment : i++ increments the loop counter i by 1 after each iteration. During each iteration, printf("%d ", i); prints the current value of i. The loop continues until the condition i <= 10 is false.
Problems & Solutions
Write a program to find the factorial of 5. The Factorial function (symbol: !) m
#include<stdio.h>
main()
{
int n,i,f=1;
printf("Enter a no:");
scanf("%d",&n);
for (i=1; i<=n; i++)
{
f=f*i;
}
printf("The factorial is=%d",f);
}
Output
Enter a no:5
The factorial is=120
Enter a no:5
The factorial is=120
Write a program to find the sum of any ten natural numbers
#include<stdio.h>
main()
{
int i,r,n,s=0;
printf("enter the range:");
scanf("%d",&r);
for(i=1; i<=r; i++)
{
scanf("%d",&n);
s=s+n;
}
printf("Sum=%d",s);
}
Output
enter the range:10
1 2 3 4 5 6 7 8 9 10
Sum=55
enter the range:10
1 2 3 4 5 6 7 8 9 10
Sum=55
Write a program to print a numbers from Fibonacci series. In Fibonacci series, n
#include<stdio.h>
main()
{
int i,a=0,b=1,c;
printf("%d ",a);
printf("%d ",b);
for(i=1; i<=10; i++)
{
c=a+b;
printf("%d ",c);
a=b;
b=c;
}
}
Output
0 1 1 2 3 5 8 13 21 34 55 89
0 1 1 2 3 5 8 13 21 34 55 89
Conclusion
The for loop is a powerful and flexible tool in C for iterating over a range of values or executing code a fixed number of times. Understanding its syntax and variations allows you to handle many programming tasks efficiently.