Programming in C

(Barry) #1

126 Chapter 8 Working with Functions


Program 8.5 Output
The gcd of 150 and 35 is 5
The gcd of 1026 and 405 is 27
The gcd of 83 and 240 is 1

The function gcdis defined to take two integer arguments.The function refers to these
arguments through their formal parameter names uand v. After declaring the variable
tempto be of type int, the program displays the values of the arguments uand v,
together with an appropriate message at the terminal.The function then calculates and
displays the greatest common divisor of the two integers.
You might be wondering why there are two printfstatements inside the function
gcd.You must display the values of uand vbeforeyou enter the whileloop because their
values are changed inside the loop. If you wait until after the loop has finished, the values
displayed for uand vdo not at all resemble the original values that were passed to the
routine. Another solution to this problem is to assign the values of uand vto two vari-
ables before entering the whileloop.The values of these two variables can then be dis-
played together with the value of u(the greatest common divisor) using a single printf
statement after the whileloop has completed.

Returning Function Results


The functions in Program 8.4 and 8.5 perform some straightforward calculations and
then display the results of the calculations at the terminal. However, you might not
always want to have the results of your calculations displayed.The C language provides
you with a convenient mechanism whereby the results of a function can be returnedto
the calling routine.This is not new to you because you’ve used it in all previous pro-
grams to return from main.The general syntax of this construct is straightforward
enough:
return expression;
This statement indicates that the function is to return the value of expressionto the
calling routine. Parentheses are placed around expressionby some programmers as a
matter of programming style, but their use is optional.
An appropriate returnstatement is not enough.When the function declaration is
made, you must also declare the type of value the function returns.This declaration is placed
immediately beforethe function’s name. Each of the previous examples in this book
defined the function mainto return an integer value, which is why the keyword intis
placed directly before the function name. On the other hand, a function declaration that
starts like this:
float kmh_to_mph (float km_speed)
begins the definition of a function kmh_to_mph, which takes one floatargument called
km_speedand which returnsa floating-point value. Similarly,
int gcd (int u, int v)
Free download pdf