for loop:
A for loop is a repetition control structure which allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line.
In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes.
- Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: int i=1;
- Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: i <= 10;
- Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: i++;
Syntax:
1.write a program to print below pattern.
* * * * *
* * * * *
* * * * *
#include<stdio.h>
void main()
{
int i,j;
for(i=0;i<=2;i++)
{
for(j=0;j<=4;j++)
{
printf("* ");
}
printf("\n");
}
}
Output:
2.write a program to print below pattern.
***
**
*
*
**
***
#include<stdio.h>
void main()
{
int i,j,k,l;
for(i=0;i<=2;i++)
{
for(j=2;j>=i;j--)
{
printf("*");
}
printf("\n");
}
for(k=0;k<=2;k++)
{
for(l=0;l<=k;l++)
{
printf("*");
}
printf("\n");
}
}
0 Comments