The Power Grid – Solution

I hope you didn’t find this month’s Exercise too difficult. I do occasionally like to toss in an easy one. But for me, the big task was getting the output just right.

In C, the pow() function outputs exponents. It’s prototyped in the math.h header file. Further, in some environments (hello, Linux), you must link in the math library when building the program: Use the -lm switch, where -l (little L) specifies a library and m is the math library. This switch must be specified last at the command prompt.

To output the table neat and tidy, I use a printf() statement inside the nested loop. The goal is to generate the cells in the table:

printf("%d^%d = %4.0f\t",a,b,pow(a,b));

The %4.0f placeholder ensures that each floating point value is output in a width of 4 characters with no characters output after the decimal. This placeholder is followed by the \t (tab) character, which aligns the cells.

Here is the full code for my solution:

2021_11-Exercise.c

#include <stdio.h>
#include <math.h>

int main()
{
    int a,b;

    for( a=0; a<7; a++ )
    {
        for( b=1; b<=5; b++ )
        {
            printf("%d^%d = %4.0f\t",a,b,pow(a,b));
        }
        putchar('\n');
    }

    return(0);
}

See? Not bad — once you get the printf() formatting done properly.

I hope your solution also met with success and that you explored possibilities for different types of table formatting. More power to you if you added a header row, and special C language bonus points are awarded if you labeled the rows as well.

Leave a Reply