When You Need a Function

I believe two reasons exist for creating functions. The first is repetition; when you have a chunk of code that duplicates several times, it’s best to shove it off into a function where it can be called repeatedly. The second reason is readability.

As an example of readability, I recently wrote a program that featured several statements in the main() function that initialize various parts of the program. To make the code more readable, I cut all those statements and placed them into an initialize() function. That way the main() main function is rather brief, and that single statement — and its definition elsewhere in the code — is self-descriptive.

For this month’s exercise, your task is to create one or more functions based on repetition as well as readability. Your job is to take the sample code, shown below, and create self-documenting functions that perform repetitive tasks:

#include <stdio.h>

int main()
{
    char name[32], color[16], quest[64];

    printf("What is your name? ");
    scanf("%s",name);
    printf("What is your favorite color? ");
    scanf("%s",color);
    printf("What is your quest? ");
    scanf("%s",quest);

    printf("%s, whose favorite color is %s, ",
            name,
            color);
    printf("you shall succeed!\n");

    return(0);
}

Yes, granted this is a short, silly program. Yet, as the program grows, functions become useful and necessary. When? That’s the point of the Exercise: Create one or more functions that reduce the length of the main() function.

Click here to view my solution. Please try this exercise on your own before you peek at what I’ve done.

Leave a Reply