Basic pattern programs in c
These programs print various patterns of numbers and stars. These codes illustrate how to create various patterns using c program. The C programs involve usage of nesting while loops (a while loop inside a while loop). A pattern of numbers or star or characters is a way of arranging these in some logical manner or they may form a sequence. Some of these patterns are triangles which have special importance in mathematics. Some patterns are symmetrical while others are not.
Example#1
#include <stdio.h>
int main()
{
int i,n,in;
printf("Enter a value: ");
scanf("%d",&n);
i=1;
while(i<=n) // Loop to print rows (outer loop)
{
printf("\n");
in=1;
while(in<=i) . // Loop to print numbers
{
printf("%d",in);
in=in+1;
}
i=i+1;
}
return 0;
}
[quote]
Output:
[/quote]
For the above program, if we change the inner loop print statement as printf("*") then print following output pattern
in=1;
while(in<=i)
{
printf("*"); //prints all '*'
in=in+1;
}
[/quote]
in=1;
while(in<=i)
{
/*
- First number of every row i.e. in == 1
- Last number of every row i.e. i == in
- Last row of pattern i.e. i== n
*/
if (in == 1 || i == in || i == n)
printf("*");
else
printf("%d",in);
in=in+1;
}
[quote]
Output:
[/quote]
in=1;
while(in<=i)
{
if(i%2 == 0) // if the row value is evern i.e. i%==2
printf("*");
else
printf("%d",in);
in=in+1;
}
[quote]
Output:
[/quote]
in=1;
while(in<=i)
{
if(in%2 == 0) // if the number value is evern i.e. i%==2
printf("*");
else
printf("%d",in);
in=in+1;
}
[quote]
Output:Enter a value: 6
[/quote]
in=1;
while(in<=i)
{
if(i%2 != in%2) // if i value even and in value is odd or vice versa
printf("*");
else
printf("%d",in);
in=in+1;
}
[quote]
Output:
[/quote]
in=1;
while(in<=i)
{
printf("%d",i);
in=in+1;
}
[quote]
Output:
[/quote]
Example#2 Floyd’s triangle
#include <stdio.h>
int main()
{
int i,n,in,value=1;
printf("Enter a value: ");
scanf("%d",&n);
i=1;
while(i<=n)
{
printf("\n");
in=1;
while(in<=i)
{
printf("%3d",value);
value= value + 1;
in=in+1;
}
i=i+1;
}
return 0;
}
[quote]
Output:
[/quote]
Example#3
#include <stdio.h>
int main()
{
int i,n,in;
printf("Enter a value: ");
scanf("%d",&n);
i=1;
while(i<=n)
{
printf("\n");
in=i;
while(in>=1)
{
printf("%d",in);
in=in-1;
}
i=i+1;
}
return 0;
}
[quote]
Output:
[/quote]
in=1;
while(in<=i)
{
if (in%2 == 0)
printf("%d",2);
else
printf("%d",1);
in=in+1;
}
[quote]
Output:
[/quote]