08.01.2023 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7 ■ Functions

The logic for finding the HCF is the same as that used in program P5.2. The difference here is

that values for m and n will be passed to the function when it is called. In P5.2, we prompted the

user to enter values for m and n and fetched them using scanf.

Suppose the function is called with hcf(42, 24). The following occurs:

• Each of the arguments is copied to a temporary memory location.

These locations are passed to the function hcf where 42 is labeled with m,

the first parameter, and 24 is labeled with n, the second parameter. We can

picture this as:

m 42 n 24

• The while loop is executed, working out the HCF. On exit from the loop,

the HCF is stored in m, which will contain 6 at this time. This is the value

returned by the function to the place from where it was called.

• Just before the function returns, the locations containing the arguments are

thrown away; control then returns to the place from where the call was made.

Program P7.5 tests the function by reading pairs of numbers and printing the HCF of each

pair. The call to hcf is made in the printf statement. The program stops if either number is less

than or equal to 0.

Program P7.5

#include <stdio.h>

int main() {

int a, b;

int hcf(int, int);

printf("Enter two positive numbers: ");

scanf("%d %d", &a, &b);

while (a > 0 && b > 0) {

printf("The HCF is %d\n", hcf(a, b));

printf("Enter two positive numbers: ");

scanf("%d %d", &a, &b);

}

} //end main

//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

176

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!