C: Pyramid (for-loops)

In the previous post, I discussed about how to create a triangle using four for-loops. In this post, we will learn how to create a program which will print a pyramid using looping statements in C.

For this program, four variables will be declared as integers, let us name them as, i, j, k and n. Variable i is the counter variable for the outer loop. Variable j and k are counter variables for the inner loop, and variable n is the length of the two legs of the pyramid, where as the base of our pyramid, is 2n-1.


   int i,j,k,n;  

Variable n will be provided by the user.

   printf("Enter number of rows for pyramid: ");   
   scanf("%d", &n);   

There will be four for-loops to be used here. The outer for-loop is responsible for each row printed. 

    for(i = 1; i <= n; i++) //row loop
    {

        printf("\n");
    }

The first inner for-loop is responsible for each space printed (from the 1st count to the n-ith count). The logic of printing spaces, will be discussed later.

    for(i = 1; i <= n; i++) //row loop
    {
        for(j = 0; j < (n - i); j++) //spaces loop
            printf(" "); 
            
        printf("\n");
    }

The second inner for-loop is responsible for creating our first right triangle. We will be using our method in the previous post.

    for(i = 1; i <= n; i++) //row loop
    {
        for(j = 0; j < (n - i); j++) //spaces loop
            printf(" "); 
        for(j = 1; j <= i; j++) // left dot to center dot
            printf("*");

        printf("\n");
    }

At this point, we can see the logic behind the spaces loop (first inner loop). It is responsible for 'aligning' our triangle towards the center (instead of the left).

The third inner for-loop is responsible for creating a second right triangle - directly beside our first right triangle.

    for(i = 1; i <= n; i++) //row loop
    {
        for(j = 0; j < (n - i); j++) //spaces loop
            printf(" "); 
        for(j = 1; j <= i; j++) // left dot to center dot
            printf("*");
        for(k = 1; k < i; k++) // after center dot to rightmost dot.
            printf("*"); 
        printf("\n");
    }

Here is a sample input and output, with n is 5.



Here is the source code.

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

    return 0;
}