Center Yourself

It’s not the first thing you think of when you design output. No, it’s one of those afterthoughts, those numerous, “Hey, I could do this” moments that programmers experience time and again. In this case, the concept is centering a chunk of text.

As an example, consider code that outputs a list of information. Such as:

Event Monitor
Time    Type
02:16   Outside connection
03:45   Scheduled backup
04:21   Attempted logon

And so on, you get the idea. After messing with the code, you’re going to think, “Hello, [your name here]! How about centering that Event Monitor title? You know, fix the string so that some spaces are padded on the right. That would look cool!”

And so you hard code the title to be centered, thus:

printf("     Event Monitor\n");

which yields:

     Event Monitor
Time    Type
02:16   Outside connection
03:45   Scheduled backup
04:21   Attempted logon

Much, better, you think. Then you mess with the table, add a column, change things. And suddenly the title isn’t centered. It’s then that you figure upon writing code that automatically centers the title. After all, that’s what programs do best: automate things!

Of course, if you were an experienced programmer, you’d write the centering code when you first wanted the title centered, but that kind of anticipation takes years to learn. Trial and error is the basis of all programming inspiration. At least that’s my theory.

To solve the problem, you write a function that centers a title. As input, the function receives a string of text. It also receives an int value indicating the width within which the text must be centered. As an example:

center("Event Monitor",40);

The above statement calls the center() function with the text Event Monitor and the int value 40. The function centers the text within 40 positions, or “spaces.” It outputs the text with a calculated number of spaces that make it more-or-less centered. (It’s “more-or-less” because text values are integers and you can’t exactly center text that doesn’t divide evenly by two.)

Below you see a source code skeleton. This month’s exercise is to add the center() function to the skeleton.

#include <stdio.h>

#define W 64

void center(char *,int);

int main()
{
    center("The Phantom Meanace",W);
    center("The Clone Wars",W);
    center("Revenge of the Sith",W);
    center("Star Wars",W);
    center("The Empire Strikes Back",W);
    center("Return of the Jedi",W);

    return(0);
}

void center(char *text,int width)
{
}

I’ve defined W as a constant so that you can experiment with different widths. The rest of the code lists strings of varying size, and you can feel free to edit them as well — especially Episodes 1 through 3.

As usual, please attempt this exercise on your own before you peek ahead at my solution. Remember also that mine is only one of many different ways in which the problem can be solved.

Exercise Solution

Leave a Reply