We are using C to print the patterns in this blog.
These kinds of pattern programs can be solved easily using for loop condition.
1) Hollow Rectangle:
#include <stdio.h>
void hollowRectangle(int n, int m)
{
int i, j;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= m; j++)
{
if (i==1 || i==n || j==1 || j==m)
printf("* ");
else
printf(" ");
}
printf("\n");
}
}
int main()
{
int rows, columns;
printf("\n Enter the number of rows : ");
scanf("%d", &rows);
printf("\n Enter the number of columns : ");
scanf("%d", &columns);
printf("\n");
hollowRectangle(rows, columns);
return 0;
}
Output:
Enter the number of rows : 5
Enter the number of columns : 5
* * * * *
* *
* *
* *
* * * * *
2) Half Pyramid Star Pattern:
#include <stdio.h>
int main()
{
int size;
printf("\n Enter size : ");
scanf("%d", &size);
for(int i = 1; i<=size; i++)
{
for(int j = 1; j <= i; j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Output:
Enter the size: 5
*
**
***
****
*****
3) Inverted Half pyramid:
#include <stdio.h>
int main()
{
int size;
printf("\n Enter size : ");
scanf("%d", &size);
for(int i = size; i >= 1; i--)
{
for(int j = 1; j <= i; j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Output:
Enter size: 5
*****
****
***
**
** * * * *
4) Full pyramid Star pattern:
#include <stdio.h>
int main() {
int i, space, rows, k = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i, k = 0) {
for (space = 1; space <= rows - i; ++space) {
printf(" ");
}
while (k != 2 * i - 1) {
printf("* ");
++k;
}
printf("\n");
}
return 0;
}
Output:
Enter the number of rows: 5
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
5) Inverted Full pyramid of * :
#include <stdio.h>
int main() {
int rows, i, j, space;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (space = 0; space < rows - i; ++space)
printf(" ");
for (j = i; j <= 2 * i - 1; ++j)
printf("* ");
for (j = 0; j < i - 1; ++j)
printf("* ");
printf("\n");
}
return 0;
}
Output:
Enter the number of rows:5
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
6) Hollow Full Pyramid:
#include <stdio.h>
int main()
{
int n;
printf("Enter number: ");
scanf("%d",&n);
int i, j, k = 0;
for (i = 1; i <= n; i++) // row=6
{
// Print spaces
for (j = i; j < n; j++) {
printf(" ");
}
// Print #
while (k != (2 * i - 1)) {
if (k == 0 || k == 2 * i - 2)
printf("*");
else
printf(" ");
k++;
;
}
k = 0;
printf("\n"); // print next row
}
// print last row
for (i = 0; i < 2 * n - 1; i++) {
printf("*");
}
}
Output:
Enter number: 5
*
* *
* *
* *
* *
*********
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Follow Programmers Door for more.
Comments