Docstoc

## Functions

Document Sample
## Functions Powered By Docstoc
					                                       Object-Oriented Programming


  Object-Oriented Programming (COM326M1)
                Lecture Week 4

                                Functions
A function in C/C++ is defined as self-contained unit of program that
performs certain task. Every C/C++ program consists of a collection
of functions. If a program is divided into functional units, then if is
possible to code each into independently, and are much easier to
code, understand, debug and test.

Any function can call any other function as well as call itself.

Example

        /* Example of a function in C */

        #include<stdio.h>
        void printline(void);
        void main( )
         {
           printline( );
           cout << “This is an example of function” << “ \n”;
           printline( );
           getch( );
         }

        printline(void)
         {
           int t;
           for(t=1;t<35;t++)
             cout << “_”;
           cout << “\n”;
         }




http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

     This program outputs the following



     This is an example of function


User-defined functions

One of the strengths of C/C++ language is that C/C++ functions are
easy to define and use.

We have used functions in every program

Example
       main( )
      {
        .
        .
      }

Example
     Printf(“This is a program \n”);

C function can be classified into two categories

                    Library functions
                    User-defined functions

Example
     Library functions are printf( ) ,scanf( ) etc.
     User-defined functions are main( ) etc.

Library functions are not required to be written by us and user-
defined functions are to be developed by the user at the time of
writing a program.

Every program must have a main function to indicate where the
program has to begin its execution.


http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

Example

        #include<stdio.h>
        int mul(int a,int b);
        void main( )
        {
           int x,y,z;
           x=10;
           y=10;
           z=mul(x,y);
           cout << mul(x,y);
           mul(x,y);
         }

        int mul(int a,int b)
         {
          return a*b;
         }

It is possible to code any program utilizing only main function but it
leads to some problems like
         Program becomes too large and complex
         As a result debugging, testing becomes difficult.

If a program is divided into functional parts, then it is possible to
code each part independently and later combined into a single unit.
These subprograms are called functions in C/C++ and are much
easier to code, understand, debug and test.

Sometimes there are operations or calculations, which required
repeating at many points throughout a program.

Example
      n ! might be used at several points in a program.

We can repeat the program statements whenever they are needed.




http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

Example

        #include<stdio.h>
        void main()
        {
          int n, t, fact ;
          cout << “Enter the number” << “\n”;
          cin<<n;
          cout << n <<“\n”;
          if(n= =0)
             cout << “Factorial of 0 is 1” << “\n”;
          else
           {
             fact=1;
             for(t=1;t<=n;t++)
               fact = fact * t;
             cout << “The factorial of “<< n, fact << “\n”;
           }
        }

Another approach is to design a function that can be called and used
whenever required, which saves both time and space. It facilitates
top-down modular programming as


                                  Main
                                 Program


  Function            Function            Function        Function


Multi-function program

A function is a self-contained block of code that performs a
particular task.




http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

Example
         printline()
        {
          int t;
          for(t=1;t<40;t++)
          cout << “_”;
          cout << “\n”;
        }

Set of statements defines a function called printline. It will output a
line like.

Prints – 39 times on the same line.


A function can be called by other functions. This function can be
used in a program as follows

        void main()
        {
           printline();
           cout << “This shows the use of C++ program” << “\n”;
           printline();
        }
        printline()
        {
          int t;
          for(t=1;t<40;t++)
          cout << “_”;
          cout << “\n”;
        }

Example
The above program contains two user-defined functions main() and
printline() and one library function printf();

While executing this program it always begins with the main
function. When it encounters printline( ); program control is
transferred to the function printline to be executed .



http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

After executing the function which outputs a line of 39 characters „
_‟, program control goes back to the main, and execution continues
at the point where the function call was executed. After executing
printf() control goes to function printline(), prints the line of 39
characters again .




http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

Control flow in a multi-function program


                                  main()
                                  {
                                  ……..;
                                  ………;
                                  function1();
                                  ……….;
                                  ………..;
                                  function2();
                                  ………..;
                                  function1();
                                  ………..;
                                  }



                                  function1()
                                  {
                                  ……..;
                                  ……..;
                                  }


                                  function2()
                                  {
                                  ……..;
                                  function3();
                                  ……….;
                                  }


                                  function3()
                                  {
                                  ………;
                                  ……….;
                                  }



http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

The form of C/C++ functions

All functions have the form

            function_name(parameter list)
        {
            local variable declaration;
            statement1;
            statement2;
            .
            .
            return (expression);
        }

Parameter list and parameter declaration parts are optional.

Local variables declaration is required only when any local variables
are used in the function.

Example
        printline()
        {
          int t;      /* Local variable */
          for(t=1;t<9;t++)
          cout << “_”;
          cout << “\n”;
        }

A function can have any number of statements or have no statement.

Example
     nothing()
     {
     }

Function name must follow the same rules as other variable names in
C and should not be any library function names, operating system
commands.



http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

Parameter list contains valid variable names separated by commas,
and enclosed with parentheses.

Example
     multi(int a,int b)
     power(a,b,)

Parameter must be declared for their types after the function header
and before opening brace of the function body.

Example
        power(x,n)
        float x;
        int n;
        {
          statement1;
          .
          .
        }

Return statement has two important uses
               It causes and immediate exit from the function i.e.
                  causes program execution to return to the calling
                  function.
               It can be used to return a value.

Returning from function

Most functions rely on the return statement to stop execution. A
function may have more than one return statement to allow multiple
exit point, based on conditions.

Example
     if(x<=0)
       return (0);
     else
       return(1);




http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

Return values

All functions (except those of type void) return a value. This value is
explicitly specified by the return statement.

Example
      mul(x,y)
       int x,y;
       {
         int p;
         p=x*y;
         return(p);
      }

It can be written as

          mul(x,y)
          int x,y;
         {
           return(x*y);
         }

If a function is not specified as void or no return value is specified,
then an unknown garbage value is returned.

As long as a function is not declared as void, it can be used as an
operand in any valid C/C++ expressions.

Example
     x=power(x,y);
     if(max(x,y) >100)
     cout << (“greater”);
     .
     .

Function is declared as void, it cannot be used in any expression.




http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

Example
     let f() be a void function
     int t;
     t=f(); is not a valid expression.
     t=f()+5; is not valid expression.

A function cannot be the target of an assignment.

Example
     swap(x,y) =100; is not valid assignment .

All functions by default return integer type date. If a function must
return some other type, we can force it to do by using a type
specified in the function header.

Example
     double product(x,y)
     float sqrt(p)

Calling a function

A function is called by simply using function name.

Example
        main()
        {
          int p;
          p=mul(10,5);
          cout << “\n” <<p;
        }

When the computer encounters the function, control is transferred to
the function mul(x,y) and then executed line by line and a value is
returned when a return statement is encountered . This value is
assigned to p.
A function, which returns a value, can be used in expressions like
any other variable.




http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

Exaample
     cout << mul(p,q) <<”\n”;
     y=mul(p,q)/(p+q);
     if(mul(p,q)>total)
         cout << “large”;

A function that does not return value can be called but cannot be
used in expressions.

Example
     {
       .
       .
       printline();
       cout << “This is a function” << “\n”;
       printline();
       .
       .
     }

Category of functions

Depending on parameters and their return values a function can
belong to one of the following categories

            Functions with no parameters and no return values
            Functions with parameters and no return values
            Functions with parameters and return values

Functions with no parameters and no return values

A function with no parameter does not receive any value from the
calling function.

Example

A program with three user-defined functions with no parameters and
no return values.



http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

Example
          main()
         {
           printline();
           value();
           printline();
        }
        /* Function printline */
         printline()
        {
          int t;
          for(t=1;t<=20;t++)
             cout << „ „;
          cout << “\n”;
        }
        /* Function value */
        value()
        {
          int yr, period;
          float interest_rate, sum , principle_amount;
          cout << “Principal amount :: ”;
          cin >> principal_amount;
          cout << “Interest rate :: ”;
          cin >> interest_rate;
          cout << “Period:: ”;
          cin >> period;
          sum = principal_amount;
          yr=1;
          while(yr<=period)
          {
            sum=sum*(1+interest_rate);
            yr++;
          }
        cout<< principal_amount, interest_rate,priod, sum;
        cout<<”\n”;
        }

Function value receives its data directly from terminal i.e. keyboard,
while loop calculates the final value and outputs it by cout <<



http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

function. When closing brace of function value() is encountered,
control goes back to calling function main.

Since every thing is clone by function printline() and value(), there
is nothing left to pass to the called function.

No return statement is used, since there is nothing to be returned and
return statement is optional.

Functions with parameters and no return values

In the above program the function main has no control over ways it
receives data, i.e. function printline prints the same line each time it
is called and the function value outputs the result each time it is
called.

We can make the calling function to input /read data from terminal /
keyboard and pass it on to the called function. This approach seems
to be wise because the calling function can check data validity.

Example

        /* Function with parameters and no return value */
        #include<stdio.h>
        void main()
        {
          int a,b,c;
          int max();
          cout << “ Enter 3 numbers :: ”;
          cin>> a, b, c;
          max(a,b,c);
        }

        int max(p,q,r)
        int p,q,r;
        {
          int largest;
          if(p>q)
           {



http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

             if(p>r)
                largest=p;
            else
                largest=r;
           }
         else if (r>q)
             largest=r;
               else
                  largest=q;
          cout << “Largest number is = ” << largest;
        }

In this category we need to modify declaration of the called functions
to include parameters as follows

Example
     printline(ch);
     value(p,r,n);

The parameters used by the called functions are called formal
parameters.

Example

The parameters in the functions printline(ch) and value(p,r,n) are
formal parameters.
              printline(ch) /* ch is formal parameter */
              value(p,r,n) /* p,r,n are formal parameter */

The calling function can only then pass values to those parameters of
the called functions.

Example
        value(500,0.12,5); /* values to pass to the called function */
        value(p,r,n); /* parameters of the called function */
         500 to be assigned to p, 0.12 to r and 5 to n respectively.

The values used by the calling functions are called actual parameters.




http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

Example
     value(500,0.12,5) /* Actual parameter */

The actual and formal parameters should match in number, type and
order i.e. the values of actual parameters are assigned to the formal
parameters on a one-to-one basis.

Example
        main()
        {
          ……..
         function1(a1,a2..am); /*function call and actual parameters*/
          ……
        }

        function1(f1,f2..fn); /*called function and formal parameters */
          ….
          ….
         {
          …..
          ….
         }

If actual parameters are more than formal parameters i.e. m>n , the
extra actual parameters are discarded.

Example
        main()
        {
          ….
          function1(a1,a2,a3,a4); /* a3,a4 are discarded */
          …..
        }

        function1(f1,f2);
          ….
          ….
         {
           …
         }



http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

If actual parameters are less than formal parameters i.e. m<n, then
unmatched formal parameters are initialised to some garbage values.
Any mismatch in data type may result in passing of garbage values
and no error message will be generated.

Formal parameters must be valid variable names. Actual parameters
may be variable names, expressions, or constants.

Example

main()
{
….
Function1(a1,2+a2,5);

}

The variables used in actual parameters must assign values before the
function call.

Example
/* program with parameters and no return values */
main()
    {
     float principal ,interest_rate;
     int period;
     cout << “Enter principal anount, interest rate and period:”;
     cin>>principal, interest_rate,period;
     printline(„_‟);
     value(principal,interest_rate,period);
     printline(„*‟);
    }
    printline(ch);
    char ch;
         {
           int t;
           for(t=1;t<=20;t++)
               cout << ch;
           cout << “\n”;


http://www.infm.ulst.ac.uk/~siddique
                                         Object-Oriented Programming

        }

        value(p,r,n)
        int n;
        float p,r;
        {
          int year;
          float sum;
          sum=p;
          year=1;
          while(year<=n)
           {
             sum = sum*(1+ r);
             year++;
           }
          cout << p,r,n,sum;
        }

Function with parameter and return values

A function should generally be coded without involving any I/O
operations. Since different program may require different output
formats for displaying results.

                 function1()       Arguments     function2(f)
                 {                               ….
                 ….                              {
                        ….                               ….
                 …..                   Return    ….
                 function2(a);         Value     return(e);
                 ….                              }
                 ….
                 }




http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

Example

/* Function with parameters and return value */
      #include<stdio.h>
      void main()
      {
      int a, b, c, largest;
      int max();
      cout << “Enter three numbers :: ”;
      cin >> a, b, c;
      largest = max(a,b,c); /* a,b,c are actual parameters */
      cout << “Largest number is ” << largest;
      }

         int max(p,q,r)
        int p,q,r;
        {
          if(p>q)
           {
             if(p>r)
                return(p);
            else
               return(r);
           }
         else if(r>q)
                  return(r);
               else
                 return(q);
        }




http://www.infm.ulst.ac.uk/~siddique
                                       Object-Oriented Programming

Functions with arrays as parameter

It is possible to pass the values of an array to a function .

Example

        #include<stdio.h>
        void main()
        {
          int A[4], t, largest;
          int max();
          cout << “Enter values of array ::” << “\n”;
          for(t=0;t<4;t++)
              cin >> A[t];
          largest = max(A,4); /* A and 4 are actual parameter */
          cout << “Largest element in array is ” << largest;
        }

        int max(a,n) /* a and n formal parameters */
        int a[ ],n;
        {
          int p, top;
          top=a[0];
          for(p=0;p<n;p++)
            {
             if(top<a[p])
             top = a[p];
             }
          return(p);
        }




http://www.infm.ulst.ac.uk/~siddique

				
DOCUMENT INFO
Jun Wang Jun Wang Dr
About Some of Those documents come from internet for research purpose,if you have the copyrights of one of them,tell me by mail vixychina@gmail.com.Thank you!