Bookmark and Share

free counters
Back to Problem list

Problem 20: Write a program to print the following pyramid:

    1 
   123
  12345
 1234567
123456789
Solution:
Actually we have to print a 5 X 9 rectangle !!!
First row has 4 spaces + 1 number + 4 spaces = 9 characters.
Second row has 3 spaces + 3 numbers + 3 spaces = 9 characters.
Third row has 2 space + 5 numbers + 2 spaces = 9 characters.
Fourth row has 1 space + 7 numbers + 1 space = 9 characters.
Fifth row has 0 space + 9 numbers + 0 space = 9 characters.

Another point to note:
First row has 1 numbers
Second row has 3 numbers
Third row has 5 numbers.
.
.
That is n th row has 2*n-1 numbers
I think you get the logic.

Source code:

#include<stdio.h>

void printSpace(int n) {
    int i;
    for(i = 0; i<n; i++) printf(" "); // printing n spaces
}

void printPyramid() {
    int i, j, sp = 4;
    for(i = 1; i<= 5; i++) { // 5 rows have to print
        printSpace(sp); // printing spaces before numbers
        for(j = 1; j<= 2*i-1; j++) {
                printf("%d",j);  // printing 2n-1 number for nth row
        }
        printSpace(sp);  // printing spaces after numbers              
        sp--;
        printf("\n");
    }
}
int main() {
    printPyramid();
    return 0;
}


Back to Problem list