User-Defined Functions

 I. Functions and Structured Programming  

Definition: Functions:

          are small programs that can be put together (just as building blocks) to form a larger structured program. 

          allow complicated programs to be divided into manageable pieces

          give the following advantages:

       function main() is not too complex and the program is more readable

       a programmer can focus on just a part of the program to construct, debug, and perfect it

       different people can work on different functions simultaneously

       once written, a function could be used many times in a program, or different programs  

 II. Standard Functions 

Definition: A standard function is a function that is provided by C++. Standard functions are organized into separate libraries. For example:

          I/O functions are contained in the header file iostream

          math functions are contained in the header file cmath  

Note: In algebra a function is defined as correspondence between arguments and the unique value of the function associated with them.  

      Example:  

      f(x,y) = xy  

      so f(2,3) = 8, f(3,2) = 9, and f(4,0.5) = 2

      2, 3; 3, 2; and 4, 0.5 are arguments

      8, 9, and 2 are the corresponding values 

To use a function in C++ the correct header file has to be included and the following has to be known:

          the name of the function

          the number of parameters, if any

          the data type of each parameter

          the data type of the computed value (called the type of the function)  

Example:

#include <cmath>
 

double
side = 5.3;  
double
cubeVolume = pow(side, 3);  
 

pow(x,y) needs the header file <cmath> to be included and:

          calculates xy - for example: pow(2,3) is 8.0

          has two parameters (or arguments) x and y

          the parameters x and y are of type double

          is of the type double which means that it returns a value of the type double  

 III. User-Defined Functions  

A user-defined function is a function that is not provided by C++.
They are classified into two categories: void and value-returning functions.  

1.       Definition and call of void functions (do not have a return data type)  

//definition of the function

void functName(type1 par1, type2 par2, �) //function heading

{    

            // statements - function body

}

//call of the function in main() or other function body

functionName(actualParam1, actualParam2,�);  

Definitions:

       formal parameter - a variable declared in the function heading

       actual parameter - a variable or expression listed in a function call  

Example:  

void hello(string name)  
{               
  
cout << "Hello " << name << "!" << endl;  
}  

//call in main()  
int
main()  
{  

 
  
hello("George");  
 

}
 

2.   Definition and call of value-returning functions (have a return data type)  

//definition of the function

functType functName(type1 par1, �) //function heading

{ 

//statements � function body

   return (expression_of_type_functType );

}

//call of the function in main() or other function body

functType var = functName(actualPar1, actualPar2,�);  

      functType � data type of the value returned by the function

          a value-returning function is called in an expression

          the expression may be part of an assignment or an output statement  

Examples:  

(1)

//Function that calculates the sum of the cubes of two numbers

int addCubes(int n1, int n2)      
{         
  
return (pow(n1,3) + pow(n2,3));  
}  

//call in main() or other function body:  
int
squaresSum = addCubes(3,5); // returns the value of (27+125)  

(2)

//Function that calculates the average of two numbers

float calculateAverage( int number1, int number2 )  
{  

  float
average; 
 
average = (number1 + number2) / 2.0; 
 
return average; 

}
                   

//call in main() or other function body:  
int
avg = calculateAverage(78,63); // returns the value of (78+63)/2  

3.   Functions without parameters  

          the formal parameter list can be empty  

          if the formal parameter list is empty

       the parentheses are still needed

       in a function call the actual parameter list is empty  

          a call to a function with an empty formal parameter list is: functionName()  

Example:  

void hello()    
{         
  
Cout << "Hello!" << endl;  
}  

// call in main()  
hello();
 

4.   The return statement  

          once a value-returning function computes the value, it has to return this value via the return statement

          the syntax of the return statement is:

            return expression_or_variable;

          when a return statement executes in a function, the function immediately terminates and the control goes back to the caller.
Note:
return statement can be used in a non-value returning function, it does not return a value but terminates the function.

          when a return statement executes in the function main(), the program terminates  

5.   Function prototype  

The function main() is usually placed before all other user-defined function.  

This could produce a compilation error because functions are compiled in the order in which they appear in the program.   

To work around this problem of undeclared identifiers, function prototypes are placed before all function definitions. 

          function prototype - function heading without the body of the function

          the syntax is:

functionType functionName(parameter list);

          the variable name in the parameter list is optional

          the data type of each parameter is required  

IV. Flow of Execution  

          the execution of a program always begins at the first statement in the function main() no matter where it is placed in the program

          other functions are executed only when they are called

          function prototypes appear before any function definition, so the compiler translates these first

          the compiler can then correctly translate a function call

          a function call statement transfers the control to the first statement in the body of this function

          after the last statement of the called function is executed, the control is passed back to the point immediately following the function call  

Example: A function that determines is a given number is prime (a number is a prime number if it divides only in 1 and in itself.)  

(1) A simple implementation of isPrime() function:  

   bool isPrime(int n) 
  
{ 
     
int i, divisors = 0; 
     
for (i = 1; i <= n; i++) 
        
if (n % i == 0) divisors++; 
     
return (divisors == 2); 

  
}
   

(2) An attempt at a more efficient isPrime()function. Some efficiency issues in previous isPrime() are:

         if the number is even, then the number is not prime

         if a divisor (different from 1 and n) is found, the algorithm has to stop

         if d1 divides n, then n = d1 x d2, and d1 or d2 < square root of n  

   bool isPrime(int n) 
  
{ 
     
int i; 
     
if (n % 2 == 0) return false; 
     
for (i = 3; i <= pow(n, 0.5); i+=2) 
        
if (n % i == 0) return false; 
     
return true; 
  
}
 

(3) Corrected implementation of isPrime()function. There are several bugs in previous isPrime():

          gives wrong Answers when n is 1 or 2

          less efficient then the first implementation � square roof on each step

          it is dangerous to depend on tests for strict equality involving floating-point numbers, because they are machine dependable approximations  

   bool isPrime(int n) 
  
{ 
     
int i, sqrtN; 
     
if (n <= 1) return false; 
     
if (n == 2) return true; 
     
if (n % 2 == 0) return false; 
     
sqrtN = pow(n, 0.5) + 1;  
     
for (i = 3; i <= sqrtN; i+=2) 
        
if (n % i == 0) return false; 
     
return true;

   }   

Programming Programming Example 25:    A program that displays all the prime numbers between 50 and 100.  

     

 #include <iostream>  
 #include
<cmath>  
using
namespace std;   
bool isPrime (int n);  
int
main()  
{ 
  
cout << "The prime numbers between 50 and 100 are: "; 
  
for (int i = 50; i <= 100; i++) 
     
if (isPrime (i)) 
        
cout << i << " ";  
  
cout << endl; 
  
return 0;  
}  

bool
isPrime (int n)  
{  

  int
i, sqrtN;  
if
(n <= 1) return false;  
if
(n == 2 ) return true;  
if
(n % 2 == 0) return false;  
sqrtN = pow((double)n, 0.5) + 1;  

for
(i = 3; i <= sqrtN; i+=2)  
if
(n % i == 0) return false;  
return
true;  
}

Programming Example 26:  A program that:

1.1. Prompts the user to input two integers: num1 and num2 (num2 must be greater than num1 with at least 20)

1.2. Outputs all odd numbers between num1 and num2

1.3. Outputs the sum of all even numbers between num1 and num2

1.4. Outputs the sum of the square of odd numbers between num1 and num2

1.5. Outputs num1 and num2 reversed

1.6. Outputs the prime numbers between num1 and num2.

 #include <iostream>  
 #include <cmath>  
using
namespace std;  
bool
isPrime (int n);  
int
main()  
{ 
  
int num1, num2, n;  
  
int sumEvens = 0, sumSqOdds = 0; 
  
int revNum1 = 0, revNum2 = 0;  
  
cout << "Please enter two numbers with the second number" << endl; 
  
cout <<  "at least 20 higher than the first: ";  
  
cin >> num1 >> num2;  
  
cout << endl;  
  
//output all the odd numbers between the inputs  
  
cout << "The odd numbers are: " << endl;  
  
for (int i=num1; i<=num2; i++) 
     
if(i % 2 != 0)  
        
cout << i << " "; 
  
//output the sum of all even numbers between the inputs  
  
for (int j = num1; j <= num2; j++) 
     
if(j % 2 == 0) 
        
sumEvens = sumEvens + j; 
  
cout << endl << "The sum of the even integers is: " << sumEvens << endl;  
  
//output the sum of the square of the odd integers  
  
for (int k = num1; k <= num2; k++) 
     
if(k % 2 != 0) 
        
sumSqOdds = sumSqOdds + (k * k); 
  
cout << "The sum of the square of the odd integers is: " << sumSqOdds << endl;  
  
//output the reverse of the inputs  
  
n = num1; 
  
do 
  
{ 
     
revNum1 = revNum1 * 10 + n % 10; 
     
n = n / 10; 
  
} while (n > 0); 
  
n = num2; 
  
do 
  
{ 
     
revNum2 = revNum2 * 10 + n % 10; 
     
n = n / 10;
  
} 
  
cout << "The reverse of the input numbers are: " << revNum1 << " and " << revNum2 << "." << endl;  
   //to output the prime numbers between the inputs 
  
cout << "The prime numbers are: "; 
  
for (int l = num1; l <= num2; l++) 
     
if (isPrime (l)) 
        
cout << l << " ";  
  
cout << endl;  

return
0;  
}

//function to determine if a number is prime  
bool
isPrime (int n)  
{  

int
i, sqrtN;  
if
(n <= 1) return false;  
if
(n == 2 ) return true;  
if
(n % 2 == 0) return false;  
sqrtN = pow((double)n, 0.5) + 1;  

for
(i = 3; i <= sqrtN; i+=2) 
        
if
(n % i == 0) return false;  
return
true;  
}