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

essentially the same code as Program P7.3. Also, printDay does not return a value so its “return

type” is void.

void printDay(int 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”);

}

■■Tip

When we write the function, we can use any variable name we want for the parameter. We never have

to worry about how the function will be called. Many beginners mistakenly believe that if the function is called

with printDay(n), the parameter in the header must be n. But that cannot be true since it could be called

with printDay(4) or printDay(n) or printDay(j) or even printDay(n + 1). The choice is up to the

calling function.

All we need to know is that whatever the value of the argument, that value will be assigned

to d (or whatever variable we happen to use as the parameter), and the function will be executed

assuming the parameter (d, in our case) has that value.

We now rewrite Program P7.3 as P7.4 to illustrate how the function fits into an overall

program and how it can be used.

Program P7.4

#include <stdio.h>

int main() {

int n;

void printDay(int);

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

scanf("%d", &n);

printDay(n);

} //end main

void printDay(int 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");

174

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!