Patterns in c - Tips and Tricks
Patterns are solved by conditional statements and mostly by loops like for loop, while loop, do while loop.
Different types of patterns in c |
Given are relevent examples based on pattern .
1)#include<stdio.h>
main()
{
int i,j;
for(j=1;j<=5;j++)
{
for(i=1;i<=j;i++)
printf("*");
printf("\n");
}
}
Output:
*
**
***
****
*****
2)#include<stdio.h>
main()
{
int i,j;
for(j=1;j<=5;j++)
{
for(i=1;i<=5;i++)
printf("*");
printf("\n");
}
}
Output:
*****
*****
*****
*****
*****
3)#include<stdio.h>
main()
{
int i,j;
for(j=1;j<=5;j++)
{
for(i=1;i<=5;i++)
if(i==1||i==5||j==1||j==5)
printf("*");
else
printf(" ");
printf("\n");
}
}
Output:
*****
* *
* *
* *
*****
4)// pyramid pattern
#include<stdio.h>
main()
{
int i,j,g,k;
for(g=5,k=1;g>=1,k<=9;g--,k=k+2)
{
for(i=1;i<=g;i++)
printf(" ");
for(j=1;j<=k;j++)
printf("*");
printf("\n");
}
}
Output:
*
***
*****
*******
*********
5)//Invert pyramid
#include<stdio.h>
main()
{
int i,j,g,k;
for(g=1,k=9;g<=5,k>=1;g++,k=k-2)
{
for(i=1;i<=g;i++)
printf(" ");
for(j=1;j<=k;j++)
printf("*");
printf("\n");
}
}
Output:
*********
*******
*****
***
*
Comments