The Power Grid

Difficulty: Easy

I enjoy programming tables, rows and columns. The standard technique is to use a nested loop. In fact, when teaching nested loops, outputting a table is par for the course.

While creating a nested loop isn’t difficult, it does take time to get the table formatting just so. I often dither on whether to add a header row, and set other various facets of table-making that can make the output more interesting and useful.

For this month’s Exercise, your challenge is to output a table of powers. It’s a grid with values zero through five across each row and values zero through six going down each column. For each cell in the table, the power of rowcolumn is calculated:

0^1 =    0	0^2 =    0	0^3 =    0	0^4 =    0	0^5 =    0	
1^1 =    1	1^2 =    1	1^3 =    1	1^4 =    1	1^5 =    1	
2^1 =    2	2^2 =    4	2^3 =    8	2^4 =   16	2^5 =   32	
3^1 =    3	3^2 =    9	3^3 =   27	3^4 =   81	3^5 =  243	
4^1 =    4	4^2 =   16	4^3 =   64	4^4 =  256	4^5 = 1024	
5^1 =    5	5^2 =   25	5^3 =  125	5^4 =  625	5^5 = 3125	
6^1 =    6	6^2 =   36	6^3 =  216	6^4 = 1296	6^5 = 7776

In the table above, which is output from my solution (and without any header row), I use the caret (^) to indicate power. The caret isn’t the power operator in the C language, though it’s used as such in other languages. For brevity’s sake I chose to use it in this table. No, in C you use the pow() function to calculate exponents. (Hint.)

This task isn’t as much about generating powers or coding a nested loop as it is to get the table to output properly, as shown above. This reason is why the table is limited in size. If not, the exponential values increase rapidly in width, making a neat table more difficult on a text screen.

Please try this Exercise on your own before you peek at my solution, which I’ll post in a week.

Leave a Reply