C Programming Examples Tutorial Index

C Loop Programs

C program to demonstrate, how you can print pyramid using for loop.
Building a pyramid in c programming is quite easy, but you must have the understanding of how for loop works.


#include <stdio.h>
#include <conio.h>
void main()
    int i, j, k, space=10;
    /*to print the pyramid in center, you can also increase the # of spaces*/
    for (i=0;i<=5;i++)
        for (k=0;k<space;k++)
         printf(" ");
        for (j=0;j<2*i-1;j++)


Program Output:



This program is used to build a pyramid using an asterisk and for that, you have to understand the for loop which is implemented inside the program. So first of all, you have to include the stdio header file using the "include" preceding # which tells that the header file needs to be process before compilation, hence named preprocessor directive. There is also another header file conio.h, which deals with console input/output and this library is used here for getch() function.

Then you have to define the main() function and it has been declared as an integer so by default it will return an integer. Inside the main() function you have to declare integer type variables name 'I', 'j', 'k', 'space' and assign the value 10 to the variable 'space'.

Now a for loop will go from i=0 till 5. Inside this, there will be another for loop which is nested for and will go from k=0 till k < space. The statement printf(" "); tells the compiler to give some designated space to the output. Another nested for loop will be implemented which will go from j=0 till j=2*i-1 and inside that loop block prints the asterisk (*) symbol. Outside the inner for loop, you have to decrement the value of variable 'space' by 1. And then printf("\n") will take the cursor to the next line on every outer loop iteration.

Finally, the getch() reads a single byte character from input and getch() is a proper way to fetch a user inputted character.

Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram