C Program To Draw Pyramid of Numbers, using For Loop


Lets write a C program to draw / display / print a four row pyramid formed from numbers 1 to 10.

Related Read:
Nested For Loop In C Programming Language
C Program To Draw Pyramid of Numbers, using While Loop

Video Tutorial: C Program To Draw Pyramid of Numbers, using For Loop


[youtube https://www.youtube.com/watch?v=Z-uVxVnXqgE]

YouTube Link: https://www.youtube.com/watch?v=Z-uVxVnXqgE [Watch the Video In Full Screen.]

Source Code: C Program To Draw Pyramid of Numbers, using For Loop

#include<stdio.h>
int main()
{
    int num = 4, row, col, space, count = 1;
    float i = -7;


    for(row = 1; row <= num; row++)
    {
        for(space = i; space <= (num-row); space++)
        {
            printf(" ");
        }
        for(col = 1; col <= row; col++)
        {
            printf(" %d ", count++);
        }
        i += 0.8;

        printf("\n");
    }

    return 0;
}

Output

                    1
                  2  3
                 4  5  6
               7  8  9  10

Logic To Draw Pyramid of Numbers, using For Loop

Here we already know that the Pyramid we need to print has 4 rows and is formed of numbers 1 to 10.

Outer for loop selects the row number and the number of elements to be printed for that particular selected row. For example, 1st row has 1 element. 2nd row has 2 elements. 3rd row has 3 elements and so on. So the row number and the number of elements in that particular row are always the same.

First inner for loop prints the adequate spacing required for the pyramid. Second inner for loop prints the actual numbers.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

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