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

The following is a sample run of P7.5:

Enter two positive numbers: 42 24

The HCF is 6

Enter two positive numbers: 32 512

The HCF is 32

Enter two positive numbers: 100 31

The HCF is 1

Enter two positive numbers: 84 36

The HCF is 12

Enter two positive numbers: 0 0

We emphasize again that even though the function is written with parameters m and n, it can

be called with any two integer values – constants, variables, or expressions. In particular, it does

not have to be called with variables named m and n. In our program, we called it with a and b.

We remind you that in order to use hcf in main, we must “declare” it using the function prototype

int hcf(int, int);

If you wish, you could write the two int declarations in main as one:

int a, b, hcf(int, int);

7.6.1 Using HCF to Find LCM

A common task in arithmetic is to find the lowest common multiple (LCM) of two numbers.

For example, the LCM of 8 and 6 is 24 since 24 is the smallest number that can divide both 8

and 6 exactly.

If we know the HCF of the two numbers, we can find the LCM by multiplying the numbers

and dividing by their HCF. Given that the HCF of 8 and 6 is 2, we can find their LCM by working out

which is 24. In general,

8 ´ 6

2

LCM(m, n) = (m x n) / HCF(m, n)

Knowing this, we can easily write a function lcm which, given two arguments m and n, returns

the LCM of m and n.

//returns the lcm of m and n

int lcm(int m, int n) {

int hcf(int, int);

return (m * n) / hcf(m, n);

} //end lcm

177

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!