For Loop
For loop is used to execute a set of statements repeatedly until a particular condition is satisfied. It is known as an open ended loop.
Syntax
for(initialization; test condition; increment/decrement)
{
block of statements;
}
- The initialization statement is executed only once.
- Then, the test expression is evaluated. If the test expression is evaluated to false, the
for loop is terminated.
- However, if the test expression is evaluated to true, statements inside the body of the
for loop
are executed, and the update expression is updated. - Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is false, the loop terminates.
Example
To calculate sum of first N natural numbers
#include <stdio.h>
#include <conio.h>
void main()
{
int num, count, sum = 0;
printf("\n Enter a positive integer: ");
scanf("%d", &num);
for(count = 1; count <= num; count++)
{
sum += count;
}
printf("\n Sum = %d", sum);
getch();
}
Output
Nested For Loop
We can also have nested for loops, i.e one
for loop
inside another for loop
.
Syntax
for(initialization; test condition; increment/decrement)
{
for(initialization; test condition; increment/decrement)
{
block of statements;
}
}
Example
#include<stdio.h>
#include <conio.h>
void main( )
{
int i, j;
for(i = 1; i < 5; i++)
{
printf("\n");
for(j = i; j > 0; j--)
{
printf("\t %d", j);
}
}
getch();
}
Output
No comments:
Post a Comment