The Inverse Pyramid – Solution

The task for this month’s Exercise was to create code that outputs an inverse number pyramid.

Here’s what such a thing looks like:

0000000000
999999999
88888888
7777777
666666
55555
4444
333
22
1


Of the many solutions, I chose to use a nested for loop: The outer loop is a simple countdown loop, going from 10 to 1. The inner loop displays a quantity digits based on the value of the outer loop: 10, 9, 8, on down to 1.

Click here to view/download the code.

Here is the line-by-line description of my solution:

#include <stdio.h>

int main()
{
    int pyramid,row;

You need two variables to create a nested for loop. pyramid is the outer variable, the one that counts down from 10 to 1. row is the inner variable, which displays the repeated numbers in the output.

    for(pyramid=10;pyramid&tg;0;pyramid--)
    {

The outer for loop counts from 10 down to 1 by using the pyramid variable. The >0 part keeps the loop spinning until 1 is reached.

        for(row=0;row<pyramid;row++)

For each repetition of the outer for loop, the inner for loop repeats. The row variable is used to count up from 0 through the value of variable pyramid.

            printf("%d",pyramid%10);
        putchar('\n');
    }

The inner loop uses a printf() function to output each value. The %d placeholder displays an int value.

The value is modified by using the % (modulus) operator. That way, the value 10 displays as 0, not 10. That’s really the key to the entire operation. The modulus operator gives the remainder of a division calculation, the left-overs. When you perform 10 % 10 you get a result of 0 because 10 evenly goes into 10.

The putchar('\n') statement adds a newline after each row is output.

You could also output the number pyramid by using an if statement, such as:

if(pyramid > 10)
    putchar('0');

That’s another solution, although the more elegant solution is to use the modulus operator. In fact, experienced programmers would refer to the if solution as a kludge, which means a clumsy work-around.