Test Your Formatting Knowledge

In late September and early October, I wrote a series of lessons on how the various printf() formatting commands are used. Now it’s time to put your skills to the test.

As a review, the four lessons covered the following aspects of the printf() function’s various conversion characters:

Integer Output (September 21)

Floating Point Output (September 28)

Text Output (October 5)

Other Output (October 12)

Feel free to reference those Lessons, which may come in handy as you try to craft code to work this month’s exercise.

To get you started, here is the program’s skeleton:

#include <stdio.h>

int main()
{   
    int age = 52;
    double nd = 16750588107179.74;
    char *name = "Barack Obama";

/* Output statements go here */

    return(0);
}

Your goal is to use various printf() statements to generate output exactly like this:

0000000000000052
34
16750588107180
1.675e+13
          Barack
Barack  

Use the three variables listed in the skeleton as the basis for the output. You cannot modify the variable’s values. Instead, use the printf() function’s conversion statements to generate the output.

As I admonish every month, please attempt to solve the exercise on your own before you peek at my solution, shown below.

Exercise Solution

Note: Yes, I’m using President Obama’s name in this code. As I’ve done since I wrote my first programming book back in the 1990s, I used the current president’s name in my examples. I did so for Bill Clinton and George W. Bush. It is not a political statement; Mr. Obama is the President and his name is well-known and up for grabs.

Oh, and 52 is his age and the nd variable value is the current US national debt.

Leave a Reply