Pattern 1:
Program:
#include <stdio.h>
int main()
{
int i, j, height=4;
for (i = 1; i <= height; i++) //outer loop
{
for (j = i; j < height; j++) //inner loop 1
{
printf(" ");
}
for (j = 1; j <= (2 * i - 1); j++) //inner loop 2
{
printf("*");
}
printf("\n"); //moves cursor to the next line
}
return 0;
}
Explanation:
In the above program, we have declared 3 variables : 'i', 'j' and 'height'.
The variables 'i' and 'j' are used to control inner and outer loops. The variable 'height' is used to define the height of the pyramid.
The outer loop is used to control the total number of rows in the pyramid.
The first inner loop is responsible for printing spaces in each row while the second inner loop is responsible for printing stars in each row.
The 'printf' statement in the outer loop is used to point cursor to the next line.
Pattern 2:
Program:
#include <stdio.h>
int main()
{
int i, j, height=4;
for (i = 1; i <= height; i++)
{
for (j = 1; j <= i; j++)
{
printf("*"); //print stars
}
printf("\n"); //moves cursor to the next line
}
return 0;
}
Explanation:
This program is used to print an inverted pyramid.
In this program, we have declared 3 variables : 'i', 'j' and 'height'.
The variables 'i' and 'j' are used to control inner and outer loops. The variable 'height' is used to define the height of the pyramid.
The outer loop is used to control the total number of rows in the pyramid.
The inner loop is responsible for printing stars in each row. The value of 'i' defines the number of stars printed in each row.
The 'printf' statement in the next is used to move the cursor to the next line.
Pattern 3:
Program:
#include <stdio.h>
int main()
{
int i, j, height=5;
for (i = 1; i <= height; i++)
{
for (j = 1; j <= height-i; j++)
{
printf("* "); //print star and a space
}
printf("\n"); //moves cursor to the next line
}
return 0;
}
Explanation:
This program prints a right-aligned triangle pattern using stars (*).
In this, we have declared 3 variables : 'i', 'j' and 'height'.
The variables 'i' and 'j' are used to control inner and outer loops. The variable 'height' is used to define the height of the pyramid.
The outer loop is used to control the total number of rows in the pyramid.
The inner loop is responsible for printing stars and a space after each star in each row.
The 'printf' statement in the next is used to move the cursor to the next line.
Pattern 4:
Program:
#include <stdio.h>
int main()
{
int i, j, height=4;
for (i = 1; i <= height; i++)
{
for (j = 1; j <= (height-i); j++)
{
printf(" ");
}
for (j = 1; j <= i; j++)
{
printf("* ");
}
printf("\n");
}
return 0;
}
Comments
Post a Comment
If there are specific topics you'd like articles on, please don't hesitate to inform me. I'll gladly publish content tailored to your preferences.