Programming in C

(Barry) #1
Functions Calling Functions Calling... 133

Program 8.8 Output


squareRoot (2.0) = 1.414216
squareRoot (144.0) = 12.000000
squareRoot (17.5) = 4.183300


The actual values that are displayed by running this program on your computer system
might differ slightly in the less significant digits.
The preceding program requires a detailed analysis.The absoluteValuefunction is
defined first.This is the same function that was used in Program 8.7.
Next, you find the squareRootfunction.This function takes one argument called x
and returns a value of type float. Inside the body of the function, two local variables
called epsilonand guessare defined.The value of epsilon, which is used to determine
when to end the iteration process, is set to .00001.The value of your guessat the
square root of the number is initially set to 1.0.These initial values are assigned to these
two variables each time that the function is called.
After the local variables have been declared, a whileloop is set up to perform the
iterative calculations.The statement that immediately follows the whilecondition is
repetitively executed as long as the absolute difference between guess^2 and xis greater
than or equal to epsilon.The expression


guess * guess - x


is evaluated and the result of the evaluation is passed to the absoluteValuefunction.
The result returned by the absoluteValuefunction is then compared against the value
of epsilon. If the value is greater than or equal to epsilon, the desired accuracy of the
square root has not yet been obtained. In that case, another iteration of the loop is per-
formed to calculate the next value of guess.
Eventually, the value of guessis close enough to the true value of the square root,
and the whileloop terminates. At that point, the value of guessis returned to the call-
ing program. Inside the mainfunction, this returned value is passed to the printffunc-
tion, where it is displayed.
You might have noticed that boththe absoluteValuefunction and the squareRoot
function have formal parameters named x.The C compiler doesn’t get confused, howev-
er, and keeps these two values distinct.
In fact, a function always has its own set of formal parameters. So the formal parame-
ter xused inside the absoluteValuefunction is distinct from the formal parameter x
used inside the squareRootfunction.
The same is true for local variables.You can declare local variables with the same
name inside as many functions as you want.The C compiler does not confuse the usage
of these variables because a local variable can only be accessed from within the function
where it is defined. Another way of saying this is that the scopeof a local variable is the
function in which it is defined. (As you discover in Chapter 11, “Pointers,” C does pro-
vide a mechanism for indirectly accessing a local variable from outside of a function.)

Free download pdf