Debugging Programs

Chapter 8 - Writing and Using Functions

Visual C++ 6: The Complete Reference
Chris H. Pappas and William H. Murray, III
  Copyright 1998 The McGraw-Hill Companies

Function Return Types
In this section, you will find an example for each of the important return types for functions possible in C and C++ programming. Function types specify the type of value returned by the function. None of the examples in the last section returned information from the function and thus were of type void.
void Return Type
Since void was used in all of the previous examples, the example for this section is a little more involved. You have learned that both C and C++ permit numeric information to be formatted in hexadecimal, decimal, and octal—but not binary. Specifying data in a binary format is useful for doing binary arithmetic or developing bit masks. The function vbinary( ) will convert a decimal number entered from the keyboard to a binary representation on the screen. The binary digits are not packed together as a single binary number, but are stored individually in an array. Thus, to examine the binary number, the contents of the array must be printed out.
/*
*   voidf.c
*   C program illustrates the void function type.
*   Program will print the binary equivalent of a number.
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>

void vbinary(int ivalue);

int main()
{
 int ivalue;

 printf(“Enter a number (base 10) for conversion to

        binary.\n”);
 scanf(“%d”,&ivalue);
 vbinary(ivalue);

 return (0);
}
void vbinary(int idata)
{
 int t=0;
 int iyourarray[50];

 while (idata !=0) {
   iyourarray[t]=(idata % 2);
   idata/=2;
   t++;
 }

 t—;
 for(;t>=0;t—)
   printf(“%1d”,iyourarray[t]);
 printf(“\n”);
}
The conversion process from higher-order to lower-order bases is a rather simple mathematical algorithm. For example, base 10 numbers can be converted to another base by dividing the number by the new base a successive number of times. If conversion is from base 10 to base 2, a 2 is repeatedly divided into the base 10 number. This produces a quotient and a remainder. The quotient becomes the dividend for each subsequent division. The remainder becomes a digit in the converted number. In the case of binary conversion, the remainder is either a 1 or a zero.
In the function vbinary( ), a while loop is used to perform the arithmetic as long as idata has not reached zero. The modulus operator determines the remainder and saves the bit in the array. Division is then performed on idata, saving only the integer result. This process is repeated until the quotient (also data in this case) is reduced to zero.
The individual array bits, which form the binary result, must be unloaded from the array in reverse order. You can observe this in the program listing. Examine the for loop used in the function. Can you think of a way to perform this conversion and save the binary representation in a variable instead of an array?
char Return Type
Let’s examine an example that is a minor variation of an earlier application. The C function clowercase( ) accepts a character argument and returns the same character type. For this example, an uppercase letter received from the keyboard is passed to the function. The function uses the library function tolower( ) (from the standard library and prototyped in CTYPE.H) to convert the character to a lowercase letter. Related functions to tolower( ) include toascii( ) and toupper( ).
/*
*   charf.c
*   C program illustrates the character function type.
*   Function receives uppercase character and
*   converts it to lowercase.
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>
#include <ctype.h>

char clowercase(char c);

int main()
{
 char clowchar,chichar;
 printf(“Enter an uppercase character.\n”);
 chichar=getchar();
 clowchar=clowercase(chichar);
 printf(“%c\n”,clowchar);

 return (0);
}

char clowercase(char c)
{
 return(tolower(c));
}
bool Return Type
The use of the new bool data type is illustrated in the following application by defining two functions, is_upper( ) and is_lower( ), that return this new ANSI C type:

/*
*  bool.c
*  C program illustrating the use
*  of the new ANSI C/C++ type bool
*  Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>

bool is_upper(void);
bool is_lower(void);

int main()
{
 char cTestChar = ‘T’;
 bool bIsUppercase, bIsLowercase;
 bIsUppercase = is_upper(cTestChar);
 bIsLowercase = is_lower(cTestChar);

 printf(“The letter %s upper case.”, bIsUppercase ? “is” :
         “isn’t”);
 printf(“the letter %s lower case.”, bIsLowercase ? “is” :
         “isn’t”);

 return(0);
}

bool is_upper(int ch)
{  
 return ( ch >= ‘A’ && ch <= ‘Z’ );
}

bool is_lower(int ch)
{
 return ( ch >= ‘a’ && ch <= ‘z’ );
}
Here the use of the conditional operator ?: is used to reduce each printf( ) statement to a single line each, instead of the more verbose if-else alternative.
int Return Type
The following function accepts and returns integers. The function icube( ) accepts a number generated in main( ) (0, 2, 4, 6, 8, 10, and so on), cubes the number, and returns the integer value to main( ). The original number and its cube are printed to the screen.
/*
*   intf.c
*   C program illustrates the integer function type.
*   Function receives integers, one at a time, and
*   returns the cube of each, one at a time.
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>

int icube(int ivalue);

int main()
{
 int k,inumbercube;
 for (k=0;k<20;k+=2) {
   inumbercube=icube(k);
   printf(“The cube of the number %d is %d \n”,
          k,inumbercube);
 }

 return (0);
}

int icube(int ivalue)
{
 return (ivalue
*ivalue*ivalue);
}
long Return Type
In the following C++ application, you’ll see how a program accepts an integer value as an argument and returns a type long. The long type, used by Visual C/C++ and other popular compilers, is not recognized as a standard ANSI C type. The function will raise the number 2 to an integer power.
//
//  longf.cpp
//  C++ program illustrates the long integer function type.
//  Function receives integers, one at a time, and
//  returns 2 raised to that integer power.
//  Copyright (c) Chris H. Pappas and William H. Murray, 1998
//

#include <iostream.h>

long lpower(int ivalue);

int main()
{
 int k;
 long lanswer;

 for (k=0;k<31;k++) {
   lanswer=lpower(k);
   cout << “2 raised to the ” << k << “ power is ”
        << lanswer << endl;
 }

 return (0);
}
long lpower(int ivalue)
{
 int t;
 long lseed=1;

 for (t=0;t<ivalue;t++)
   lseed
*=2;
 return (lseed);
}
In this application, the function simply multiplies the original number by the number of times it is to be raised to the specified power. For example, if you wanted to raise 2 to the 6
2 * 2 * 2 * 2 * 2 * 2  = 64
Can you think of a function described in MATH.H that could achieve the same results? See Table 8-1 for some ideas.
float Return Type
The following application illustrates how a float array argument will be passed to a function and a float will be returned. This C++ example will find the product of all the elements in an array.
//
//  floatf.cpp
//  C++ program illustrates the float function type.
//  Function receives an array of floats and returns
//  their product as a float.
//  Copyright (c) Chris H. Pappas and William H. Murray, 1998
//

#include <iostream.h>

float fproduct(float farray[]);

int main()
{
 float fmyarray[7]={4.3,1.8,6.12,3.19,0.01234,0.1,9876.2};
 float fmultiplied;
 fmultiplied=fproduct(fmyarray);
 cout << “The product of all array entries is: ”
      << fmultiplied << endl;

 return (0);
}

float fproduct(float farray[])
{
 int i;
 float fpartial;

 fpartial=farray[0];
 for (i=1;i<7;i++)
   fpartial
*=farray[i];
 return (fpartial);
}
Since the elements are multiplied together, the first element of the array must be loaded into fpartial before the for loop is entered. Observe that the loop in the function fproduct( ) starts at 1 instead of the normal zero value.
double Return Type
The next application shows how a program accepts and returns a double type. The function dtrigcosine( ) will convert an angle, expressed in degrees, to its cosine value.
/*
*   double.c
*   C program illustrates the double function type.
*   Function receives integers from 0 to 90, one at a
*   time, and returns the cosine of each, one at a time.
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>
#include <math.h>

const double dPi=3.14159265359;

double dtrigcosine(double dangle);
int main()
{
 int j;
 double dcosine;

 for (j=0;j<91;j++) {
   dcosine=dtrigcosine((double) j);
   printf(“The cosine of %d degrees is %19.18lf \n”,
          j,dcosine);
 }

 return (0);
}

double dtrigcosine(double dangle)
{
 double dpartial;
 dpartial=cos((dPi/180.0)
*dangle);
 return (dpartial);
}
Note that the cos( ) function found in MATH.H is used by dtrigcosine( ) for obtaining the results. Angles must be converted from degrees to radians for all trigonometric functions. Recall that pi radians equals 180 degrees.

Books24x7.com, Inc 2000 –  


Visual C++ 6(c) The Complete Reference
Visual Studio 6: The Complete Reference
ISBN: B00007FYGA
EAN: N/A
Year: 1998
Pages: 207

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