Aligned Columns

When you print a table, such as a receipt or a scoreboard, you want the columns to line up. Normally, though, each line is only as long as its text, and the numbers end up all over the place:

printf("%s %.2f\n", "Bread", 2.5);
printf("%s %.2f\n", "Chocolate", 3.75);

This prints:

Bread 2.50
Chocolate 3.75

A number between the % and the letter of a format specifier sets the width: how many characters the value takes at least. A shorter value is filled up with spaces. %10s adds the spaces on the left, so it aligns the text to the right. With a minus, %-10s, the spaces go on the right, and the text is aligned to the left, which is what you usually want for names. Numbers have widths too. The square brackets in this example show where each value starts and ends:

printf("[%5d]\n", 42);
printf("[%-5d]\n", 42);
printf("[%10s]\n", "Anna");
printf("[%-10s]\n", "Anna");
printf("[%6.2f]\n", 3.14159);

This prints:

[   42]
[42   ]
[      Anna]
[Anna      ]
[  3.14]

In %6.2f, 6 is the whole width, decimal point included, and 2 is the number of decimal places. A receipt with widths looks like this:

printf("%-10s %6.2f\n", "Bread", 2.5);
printf("%-10s %6.2f\n", "Chocolate", 3.75);

This prints:

Bread        2.50
Chocolate    3.75

A longer value isn't cut off: %3s prints "Alexander" whole, and only the alignment breaks. So choose the width by the longest value in the column. And watch out for accents: the width counts chars, so a line with "Crème" would be shifted by one place. That's why the names in this exercise have no accents.

In the exercise, the names of the items are stored in an array of strings. It's a 2D array of characters, which you know from the lesson on arrays: char items[4][12] has 4 rows, and each row is one string with room for 11 characters and the '\0'. items[1] is the whole second string, so you print it with %s:

char items[4][12] = {"Bread", "Milk", "Chocolate", "Tea"};
printf("%s\n", items[1]);

This prints:

Milk

Instructions

Change the format string in the loop: align the names to the left in a column 10 characters wide, %-10s, and the prices to the right in a column 6 characters wide with 2 decimal places, %6.2f. Leave one space between the columns. The output will look like this:

Bread        2.50
Milk         1.20
Chocolate    3.75
Tea          4.10

Below the loop, print a line with the total: the text Total in a column as wide as the names, and the sum of the prices in a column as wide as the prices. Add up the prices in the loop. The line will look like this:

Total       11.55

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

9/10