C program to print pyramid pattern of numbers

In this article, I write a c program to print pyramid pattern of numbers and explain to you how the c program works.

 

C program to print pyramid pattern of numbers

 

C program to print pyramid pattern of numbers

 

Let’s write a c program to print pyramid patterns of numbers.


#include <stdio.h>

int main()

{

   int i, j, n;
   printf("Enter the number of rows: ");
   scanf("%d", &n);

  for(i=1; i<=n; i++)
  {

for(j=1; j<=n-i; j++)

printf(" ");

for(j=1; j<=i; j++)

printf("%d ", j);

printf("\n");

}

return 0;

}

 

Output –

The program takes input from the user on the number of rows you want to print and it prints the number pyramid on the c console like below –

 

C program to print pyramid pattern of numbers

Here the user has entered input 10 you can change the input as see the result.

 

How the program works –

 

The program uses two nested for loops to print a pyramid pattern of numbers.

 

  • The outer for loop for(i=1; i<=n; i++) is used to control the number of rows. The value of n is entered by the user.
  • The inner for loop for(j=1; j<=n-i; j++) is used to print spaces before each row. The number of spaces is calculated as n – i, where n is the total number of rows and i is the current row number.
  • The second inner for loop for(j=1; j<=i; j++) is used to print the numbers in each row. The numbers are printed from 1 to i, the current row number.
  • After printing each row, a new line is printed using printf(“\n”) to move to the next row.
  • Finally, the program returns 0, indicating that it has been executed successfully.

 

Conclusion

 

I hope now you are able to write a c program to print pyramid patterns of numbers. Here the important point to learning the nested for loops it allows us to print a pyramid pattern with the desired number of rows.

Without nested for loops, it would be more difficult to print the pyramid pattern, as we would need to write separate code for each row to print the spaces and numbers.