CSC261 Jan24

slide version

single file version

Contents

  1. Functions
  2. C++ Function Example
  3. Predefined Functions
  4. User Defined Functions
  5. Skeleton for Writing a Function
  6. Example: No Function
  7. Writing a Square Root Function
  8. Terms Associated with Calling a Function
  9. Terms Associated with Writing a Function
  10. Function Declarations
  11. Function Definitions
  12. Functions that don't return a value
  13. What are "local" variables?

Functions[1] [top]

C++ Function Example[2] [top]

At line 17,

                       argument
                          |
                          | 
          y    =    sqrt( i );
                    |       |
                    +-------+
                        |
                   function call
                
                    
    1	#include <iostream>
    2	#include <iomanip>
    3	#include <cmath>
    4	
    5	using namespace std;
    6	
    7	int main()
    8	{
    9	  double y;
   10	
   11	  cout.setf(ios::fixed);
   12	  cout.precision(4);
   13	
   14	  cout << setw(10) << "Number"
   15	       << setw(13) << "Square Root" << endl;
   16	  for(int i = 1; i <= 10; i++) {
   17	    y = sqrt((double) i);
   18	    cout << setw(10) << i
   19		 << setw(13) << y << endl;
   20	  }
   21	
   22	  cout << endl << endl;
   23	  return 0;
   24	}

Predefined Functions[3] [top]

User Defined Functions[4] [top]

Skeleton for Writing a Function[5] [top]

return_type  function_name (  argument_list ) {
   local declarations

   initializations

   processing statements

   return statement
}

Example: No Function[6] [top]

Here is the example program that computed square roots without using the predefined sqrt function:

    1	int main()
    2	{
    3	
    4	  double x, y;
    5	  cout << "Enter a positive number: ";
    6	  cin >> x;
    7	
    8	  y = ( 1.0 + x ) /2;
    9	
   10	  while( fabs(x - y * y) > 0.0001 ) {
   11	    y = (y + x/y)/2;
   12	  }
   13	  cout.setf(ios::fixed);
   14	  cout.precision(4);
   15	
   16	  cout << "x = " << x << endl;
   17	  cout << "y = " << y << endl;
   18	  cout << "y*y = " << y * y << endl;
   19	
   20	  return 0;
   21	}

Writing a Square Root Function[7] [top]

(In class)

Terms Associated with Calling a Function[8] [top]

Terms Associated with Writing a Function[9] [top]

Function Declarations[10] [top]

Function Definitions[11] [top]

Functions that don't return a value[12] [top]

What are "local" variables?[13] [top]