20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Return<strong>in</strong>g Function Results<br />

127<br />

def<strong>in</strong>es a function gcd with <strong>in</strong>teger arguments u and v that returns an <strong>in</strong>teger value. In<br />

fact, you can modify Program 8.5 so that the greatest common divisor is not displayed<br />

by the function gcd but is <strong>in</strong>stead returned to the ma<strong>in</strong> rout<strong>in</strong>e, as shown <strong>in</strong><br />

Program 8.6.<br />

Program 8.6<br />

F<strong>in</strong>d<strong>in</strong>g the Greatest Common Divisor and Return<strong>in</strong>g the Results<br />

/* Function to f<strong>in</strong>d the greatest common divisor of two<br />

nonnegative <strong>in</strong>teger values and to return the result */<br />

#<strong>in</strong>clude <br />

<strong>in</strong>t gcd (<strong>in</strong>t u, <strong>in</strong>t v)<br />

{<br />

<strong>in</strong>t temp;<br />

while ( v != 0 ) {<br />

temp = u % v;<br />

u = v;<br />

v = temp;<br />

}<br />

}<br />

return u;<br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

<strong>in</strong>t result;<br />

result = gcd (150, 35);<br />

pr<strong>in</strong>tf ("The gcd of 150 and 35 is %i\n", result);<br />

result = gcd (1026, 405);<br />

pr<strong>in</strong>tf ("The gcd of 1026 and 405 is %i\n", result);<br />

pr<strong>in</strong>tf ("The gcd of 83 and 240 is %i\n", gcd (83, 240));<br />

}<br />

return 0;<br />

Program 8.6 Output<br />

The gcd of 150 and 35 is 5<br />

The gcd of 1026 and 405 is 27<br />

The gcd of 83 and 240 is 1

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

Saved successfully!

Ooh no, something went wrong!