A Loop Example Using a Function Return Value

I l @ ve RuBoard

A Loop Example Using a Function Return Value

For the last example in this chapter, you'll design a function that calculates the result of raising a number to an integer power. (For the serious number-cruncher, the math.h library provides a more powerful power function called pow() that allows floating-point exponents.) The three main tasks in this exercise are devising the algorithm for calculating the answer, expressing the algorithm in a function that returns the answer, and providing a convenient way of testing the function.

First, let's look at an algorithm. Keep the function simple by restricting it to positive integer powers. Then, if you want to raise a to the b power, you have to multiply a times itself b times. This is a natural task for a loop. You can set a variable pow to 1 and then multiply it by a repeatedly:

 for(i = 1; i <= b; i++)      pow *= a; 

Recall that the *= operator multiplies the left side by the right side. After the first loop cycle, pow is 1 times a , or a . After the second cycle, pow is its previous value ( a ) times a , or a squared, and so on. The for loop is natural in this context because the loop is executed a predetermined (after b is known) number of times.

Now that you have an algorithm, you should decide which data types to use. The exponent b , being an integer, should be type int . To allow maximum range in values for a and its power, make a and pow type double .

Next , let's consider how to put the function together. You need to give the function two values, and the function should give back one. To get information to the function, you can use two arguments, one double and one int , specifying which number to raise to what power. How do you arrange for the function to return a value to the calling program? To write a function with a return value, do the following:

  1. When you define a function, state the type of value it returns.

  2. Use the keyword return to indicate the value to be returned.

For example, you can do this:

 double power(double a, int b)  /* power() returns type double */ {   double pow = 1.0;   int i;   for(i = 1; i <= b; i++)        pow *= a;   return pow;                  /* return the value of pow     */ } 

To declare the function type, preface the function name with the type, just as you do when declaring a variable. The keyword return causes the function to return the following value to the calling function. Here you return the value of a variable, but you can return the value of expressions, too. For instance, the following is a valid statement:

 return 2 * x + b; 

The function would compute the value of the expression and return it. In the calling function, the return value can be assigned to another variable, can be used as a value in an expression, can be used as an argument to another function, as in printf("%f", power(6.28, 3)) , or can be ignored.

Now let's use the function in a program. To test the function, it would be convenient to be able to feed several values to the function to see how the function reacts. This suggests setting up an input loop. The natural choice is the while loop. You can use scanf() to read in two values at a time. If successful in reading two values, scanf() returns the value 2 , so you can control the loop by comparing the scanf() return value to 2. One more point: To use the power() function in your program, you need to declare it, just as you declare variables that the program uses. Listing 6.18 shows the program.

Listing 6.18 The power.c program.
 /* power.c -- raises numbers to integer powers */ #include <stdio.h> double power(double a, int b);  /* ANSI prototype */ int main(void) {   double x, xpow;   int n;   printf("Enter a number and the positive integer power");   printf(" to which\nthe number will be raised. Enter q");   printf(" to quit.\n");   while (scanf("%lf%d", &x, &n) == 2)   {        xpow = power(x,n);       /* function call           */        printf("%.3g to the power %d is %.5g\n", x, n, xpow);        printf("Enter next pair of numbers or q to quit.\n");   }   printf("Hope you enjoyed this power trip -- bye!\n");   return 0; } double power(double a, int b)   /* function definition     */ {   double pow = 1;   int i;   for(i = 1; i <= b; i++)        pow *= a;   return pow;                  /* return the value of pow  */ } 

If your compiler doesn't recognize the ANSI forms, you can use the following declaration and function header:

 double power();                /* declaration */ double power(a,b);             /* header      */ double a; int b; 

Here is a sample run:

 Enter a number and the positive integer power to which the number will be raised. Enter q to quit.  1.2 12  1.2 to the power 12 is 8.9161 Enter next pair of numbers or q to quit.  2 16  2 to the power 16 is 65536 Enter next pair of numbers or q to quit.  q  Hope you enjoyed this power trip -- bye! 

Program Discussion

The main() program is an example of a driver , a short program designed to test a function.

The while loop is a generalization of a form you've used before. Entering 1.2 12 causes scanf() to read two values successfully and to return 2 , and the loop continues. Because scanf() skips over whitespace, input can be spread over more than one line, as the sample output shows, but entering q produces a return value of because q can't be read using the %lf specifier ; this causes scanf() to return , terminating the loop. Similarly, entering 2.8 q would produce a return value of 1 ; that, too, would terminate the loop.

Now let's look at the function- related matters. The power() function appears three times in this program. The first appearance is this:

 double power(double a, int b);     /* ANSI prototype */ 

This statement announces, or declares, that the program will be using a function called power() . The initial keyword double indicates that the power() function returns a type double value. The compiler needs to know what kind of value power() returns so that it will know how many bytes of data to expect and how to interpret them; this is why you have to declare the function. The double a, int b within the parentheses means that power() takes two arguments. The first should be a type double value, and the second should be type int .

The second appearance is this:

 xpow = power(x,n);   /* function call */ 

Here you call the function, passing it two values. The function calculates the nth power of x and returns it to the calling program, where the return value is assigned to the variable xpow .

The third appearance is in the head of the function definition:

 double power(double a, int b)   /* function definition */ 

Here power() takes two arguments: a double and an int , represented by the variables a and b . Note that power() is not followed by a semicolon when it appears in a function definition, but is followed by a semicolon when in a function declaration. After the function heading comes the code that specifies what power() does.

Recall that the function uses a for loop to calculate the value of a to the b power and assign it to pow . The following line makes the value of pow the function return value:

 return pow;         /* return the value of pow */ 

Using Functions with Return Values

Declaring the function, calling the function, defining the function, using the return keyword: These are the basic elements in defining and using a function with a return value.

At this point, you might have some questions. For example, if you are supposed to declare functions before you use their return values, how come you used the return value of scanf() without declaring scanf() ? Why do you have to declare power() separately when your definition of it says it is type double ?

Let's take the second question first. The compiler needs to know what type power() is when it first encounters power() in the program. At this point, the compiler has not yet encountered the definition of power() , so it doesn't know that the definition says the return type is double . To help out the compiler, you preview what is to come by using a forward declaration . This declaration informs the compiler that power() is defined elsewhere and that it will return type double . If you place the power() function definition ahead of main() in the file, you can omit the forward declaration because the compiler would have known all about power() before reaching main() . However, that is not standard C style. Because main() usually provides the overall framework for a program, it's best to show main() first. Also, functions often are kept in separate files, so a forward declaration is essential.

Next, why didn't you declare scanf() ? Well, you did. The stdio.h header file has function declarations for scanf() , printf() , and several other I/O functions. The scanf() declaration states that it returns type int . However, if you forget to include stdio.h , the program still works. That's because C assumes that if you don't declare the type for a function, it is type int . Early C programming often relied heavily on this assumption, but modern practice is to declare the function type even if it is int . Future practice, as proposed by the C9X committee, drops the automatic assumption of type int , so that is an even stronger reason to be explicit.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net