C Program to Print Pyramid Patterns

Get Certified in C Programming and Take Your Skills to the Next Level

Pyramid patterns are an interesting and popular programming exercise for beginners learning the C programming language. These patterns involve printing a series of lines or rows in a pyramid shape, with each row containing a specific pattern of characters. In this article, we will explore how to write a C program to print various pyramid patterns, along with the corresponding code and results.

C Program to Print Pyramid Patterns

Pattern 1: Half Pyramid Pattern in C

Let’s start with a simple half pyramid pattern where each row contains an increasing number of asterisks (`*`).

#include <stdio.h>
int main() {
int dataflair, i, j;
printf("Enter the number of rows: ");
scanf("%d", &dataflair);
for (i = 1; i <= dataflair; i++) { for (j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}

Output:

Enter the number of rows: 4
*
* *
* * *
* * * *

Pattern 2: Inverted Half Pyramid Pattern in C

Next, let’s consider an inverted half pyramid pattern, where each row contains a decreasing number of asterisks (`*`).

#include <stdio.h>
int main() {
int rows, i, j;
printf("Enter the number of rows: ");
scanf("%d", &dataflair);

for (i = dataflair; i >= 1; i--) { 
for (j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}

Output:

Enter the number of rows: 4
* * * *
* * *
* *
*

Pattern 3: Inverted Full Pyramid Pattern in C

Lastly, let’s explore an inverted full pyramid pattern, where each row contains spaces and asterisks (`*`) to form an upside-down pyramid.

#include <stdio.h>
int main() {
int dataflair, i, j, space;
printf("Enter the number of rows: ");
scanf("%d", &dataflair);
for (i = dataflair; i >= 1; i--) {
for (space = 1; space <= dataflair - i; space++) { 
printf(" ");
}
for (j = 1; j <= 2 * i - 1; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}

Output:

Enter the number of rows: 4
* * * * * * *
* * * * *
* * *
*

Conclusion:

These are just a few examples of pyramid patterns that can be printed using C programming. You can modify the code provided to create more complex patterns or experiment with different characters.

By practising these patterns, you can gain a better understanding of loop structures, conditional statements, and how to manipulate output in the C programming language. Have fun exploring and enhancing your programming skills!

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *