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

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

else printf("Invalid day\n");

} //end printDay

Now that we have delegated the printing to a function, notice how main is much less

cluttered. However, we do have to write the function prototype for printDay in main so that

printDay can be called from main. Here is the prototype:

void printDay(int);

As with all C programs, execution begins with the first statement in main. This prompts the user

for a number, and the program goes on to print the name of the day by calling the function printDay.

A sample run is:

Enter a day from 1 to 7: 4

Wednesday

In main, suppose n has the value 4. The call printDay(n) is executed as follows:

• The value of the argument n is determined. It is 4.

• The value 4 is copied to a temporary memory location. This location is

passed to the function printDay where it is labeled with the name of the

parameter, d. In effect, d is set to the value of the argument.

• The body of the function is executed. In this case, since d is 4, the statement

printf("Wednesday\n") will be executed.

• After printing Wednesday, the function is finished. The location containing

the argument is discarded and control returns to main to the statement

following the call printDay(n). In this case, there are no more statements so

the program ends.

7.6 Highest Common Factor

In Chapter 5, we wrote Program P5.2, which read two numbers and found their highest common

factor (HCF). You should refresh your memory by taking a look at the program.

It would be nice if whenever we want to find the HCF of two numbers (m and n, say), we could

make a function call hcf(m, n) to get the answer. For instance, the call hcf(42, 24) would return

the answer 6. To be able to do this, we write the function as follows:

//returns the hcf of m and n

int hcf(int m, int n) {

while (n != 0) {

int r = m % n;

m = n;

n = r;

}

return m;

} //end hcf

175

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!