In C Programing, A loop is a repeating of statement until a specific condition is satisfied. There are mainly three types of loops are used in C language.
- for loop
- while loop
- do...while loop
for loop
Syntax of for loop :
for (initialization Statement; test condition; increment of Statement)
{
// statements of loop
}
This is loop which is used frequently in c Language.
Flow Diagram of For loop
Note : In C language, we can not declare the variable in condition and We can initialize more than one variable in Expression .
Step 1: In Initialization expression we initialize the loop variable to some values. e.g. int i=1.
Step 2: If the test condition is evaluated and test condition is evaluated to false, the for loop is terminated.
Step 3: If the test expression successful executed in loop body and variable incremented or decremented, depending on the operation (++ or –).
Step 4: Again the test condition is evaluated .
Example : Find the sum of first n natural numbers (for loop)
// find the sum of first n natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when num is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
Output:
Enter a positive integer: 10
Sum = 55
0 Comments