08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7 ■ Functions

As written, max returns the larger of two integers. What if we want to find the larger of two

double numbers? Could we use max? Unfortunately, no. If we called max with double values as

arguments, we may get strange results when a double number is assigned to an int parameter.

On the other hand, if we wrote max with double parameters and double return type, it would

work for both double and int arguments, since we can assign an int value to a double parameter

without losing any information.

Note, however, that if we call max with two character arguments, it would work by returning

the larger of the two codes. For example, max('A', 'C') will return 67, the code for C.

Exercise

Write functions to return the smaller of two integers and two floating-point numbers.

7.5 Print the Day

Let us write a program that requests a number from 1 to 7 and prints the name of the day of the

week. For example, if the user enters 5, the program prints Thursday. Program P7.3 does the job

using a series of if...else statements.

Program P7.3

#include <stdio.h>

int main() {

int d;

printf("Enter a day from 1 to 7: ");

scanf("%d", &d);

if (d == 1) printf("Sunday\n");

else if (d == 2) printf("Monday\n");

else if (d == 3) printf("Tuesday\n");

else if (d == 4) printf("Wednesday\n");

else if (d == 5) printf("Thursday\n");

else if (d == 6) printf("Friday\n");

else if (d == 7) printf("Saturday\n");

else printf("Invalid day\n");

}

Now suppose that printing the name of a day of the week was a small part of a much larger

program. We wouldn’t want to clutter up main with this code nor would we want to rewrite this

code every time we needed to print the name of a day. It would be much nicer if we could write

printDay(n) and get the appropriate name printed. We would be able to do this if we write a

function printDay to do the job.

The first thing to ask is what information does printDay need to do its job. The answer is

that it needs the number of the day. This immediately suggests that printDay must be written

with the number of the day as a parameter. Apart from this, the body of the function will contain

173

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!