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

When main is executed,

• printf prints a heading

• The for loop is executed with n assuming the values 0, 1, 2, 3, 4, 5, 6, 7. For

each value of n, factorial is called with n as its argument. The factorial is

calculated and returned to the place in printf from where it was called.

We have deliberately used a variable called n in main to illustrate that this n does not (and

cannot) conflict with the parameter n of factorial. Suppose n in main is stored in memory

location 865 and has the value 3. The call factorial(n) stores the value of n, i.e. 3, in a temporary

location (472, say) and this temporary location is passed to factorial where it is known as n. This

is illustrated as follows:

865 3 472 3

n in main

n in factorial

We now have two locations called n. When in factorial, n refers to location 472; when in

main, n refers to location 865; factorial has no access whatsoever to location 865.

It does not happen here, but if factorial were to change the value of n, it is the value in

location 472 that would be changed; the value in location 865 would not be affected. When

factorial finishes, location 472 is discarded – that n no longer exists.

From another point of view, factorial is oblivious to the actual argument that was used to

call it since it sees only the argument’s value, not how it was derived.

We used n in main as a loop variable to illustrate the point above. However, we could have

used any variable. In particular, we could have used h and there would be no conflict with the

local variable h of the function factorial. When in factorial, h refers to the local variable; when

in main, h refers to the h declared in main.

7.7.2 Combinations

Suppose there are 7 people on a committee. How many subcommittees of 3 people can be

formed? The answer is denoted by 7 C 3

and calculated as follows:

7!

4! 3!

This gives us a value of 35. We say there are 35 combinations of 7 objects taken 3 at a time.

In general, n C r

denotes the number of combinations of n objects taken r at a time and is

calculated by the formula:

n!

n-

r ! r !

( )

182

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!