Programming in C

(Barry) #1
Arguments and Local Variables 125

where the value 10 becomes the value of the formal parameter ninside the function.The
function then proceeds to calculate the value of the 10th triangular number and display
the result.
The next time that calculateTriangularNumberis called, the argument 20 is passed.
In a similar process, as described earlier, this value becomes the value of ninside the
function.The function then proceeds to calculate the value of the 20th triangular num-
ber and display the answer at the terminal.
For an example of a function that takes more than one argument, rewrite the greatest
common divisor program (Program 5.7) in function form.The two arguments to the
function are the two numbers whose greatest common divisor (gcd) you want to calcu-
late. See Program 8.5.


Program 8.5 Revising the Program to Find the Greatest Common Divisor


/ Function to find the greatest common divisor
of two nonnegative integer values
/


#include <stdio.h>


void gcd (int u, int v)
{
int temp;


printf ("The gcd of %i and %i is ", u, v);

while ( v != 0 ) {
temp = u % v;
u = v;
v = temp;
}

printf ("%i\n", u);
}


int main (void)
{
gcd (150, 35);
gcd (1026, 405);
gcd (83, 240);


return 0;
}

Free download pdf