Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use

 

Style 4: non-void functionName(arguments)

Our fourth style of function takes arguments AND returns a value.  

//Example program with driver and function
//Screen display shown at the bottom
//A minimum value function

#include<iostream.h>
#include<stdlib.h>

int min(int x, int y);   //function prototype

int main(void)     // driver program
{
     system("CLS");
     int test1 = 12, test2 = 10;  //
arbitrary test values   
     cout<<"The minimum of "<< test1 << " and " << test2
           << " is " << min(test1, test2) << ".\n";
      return 0;
}

//function definition  
int min(int x, int y)
{
     int minimum;    
     if (x < y)
          minimum = x;
     else
          minimum = y;
     return (minimum);

Alternative codings for this function appear at the right.  Remember, there are always many ways to accomplish a task.

 

Screen Display:

The minimum of 12 and 10 is 10.

 

 

  

NOTE:
A short program designed to test a function is called a driver.

 

Alternative Function Code
(uses conditional operator)

int min(int x, int y)
{
   return((x<y)? x : y);
}

 

Alternative Function Code
(uses multiple returns)

int min(int x, int y)
{
   if (x < y)
       return x;
   else
        return y;
}

 

 Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use