16066 functions

Upload: er-ashish-baheti

Post on 14-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 16066 Functions

    1/67

  • 7/29/2019 16066 Functions

    2/67

    What is function???? Function is a self contained block of statements that

    perform a coherent task of some kind.

    Every C program can be a thought of the collection offunctions.

    main( ) is also a function.

  • 7/29/2019 16066 Functions

    3/67

    Types of Functions.

    Library functions

    These are the in- -built functions of C library.

    These are already defined in header files. e.g. printf( ); is a function which is used to print at

    output. It is defined in stdio.h file .

    User defined functions.

    Programmer can create their own function in C toperform specific task

  • 7/29/2019 16066 Functions

    4/67

    Why use functions?Writing functions avoids rewriting of the same code

    again and again in the program.

    Using function large programs can be reduced tosmaller ones. It is easy to debug and find out the errorsin it.

    Using a function it becomes easier to write program to

    keep track of what they are doing.

  • 7/29/2019 16066 Functions

    5/67

    Function Declarationret_type func_name(data_type par1,data_type par2);

    Function Definationret_type func_name(data_type par1,data_type par2)

    {

    }

    Function Call

    func_name(data_type par1,data_type par2);

  • 7/29/2019 16066 Functions

    6/67

    Function prototypeA prototype statement helps the compiler to check the

    return type and arguments type of the function.

    A prototype function consist of the functions returntype, name and argument list.

    Example

    int sum( int x, int y);

  • 7/29/2019 16066 Functions

    7/67

    Example#include#include

    void main(){clrscr();

    void print(); /*func declarationprint(); /*func callingprintf(no parameter and no return value);print();getch();}

    void print() /*func defination{

    For(int i=1;i

  • 7/29/2019 16066 Functions

    8/67

    #include

    void main(){clrscr();int a=10,b=20;int sum(int,int);

    int c=sum(a,b); /*actual argumentsCout

  • 7/29/2019 16066 Functions

    9/67

    Function parameters The parameters are local variables inside the body of

    the function.

    When the function is called they will have the valuespassed in.

    The function gets a copy of the values passed in (we willlater see how to pass a reference to a variable).

  • 7/29/2019 16066 Functions

    10/67

    Arguments/Parametersone-to-one correspondence between the

    arguments in a function call and the

    parameters in the function definition.int argument1;double argument2;// function call (in another function, such as main)result = thefunctionname(argument1, argument2);

    // function definitionint thefunctionname(int parameter1, double parameter2){// Now the function can use the two parameters// parameter1 = argument 1, parameter2 = argument2

  • 7/29/2019 16066 Functions

    11/67

    a) Actual arguments:-the arguments of calling functionare actual arguments.

    b) Formal arguments:-arguments of called function areformal arguments.

    c) Argument list:-means variable name enclosed withinthe paranthesis.they must be separated by comma

    d) Return value:-it is the outcome of the function. theresult obtained by the function is sent back to thecalling function through the return statement.

  • 7/29/2019 16066 Functions

    12/67

    Return statement It is used to return the value to the calling function.

    It can be used in fallowing ways

    a) return(expression) return(a+b);b) A function may use one or more return statement

    depending upon condition

    if(a>b)

    return(a);else

    return(b);

  • 7/29/2019 16066 Functions

    13/67

    c) return(&a); returns the address of the variable

    d)returns(*p);returns value of variable through the

    pointere)return(sqrt(r));

    f)return(float (sqrt(2.4)));

  • 7/29/2019 16066 Functions

    14/67

    Categories of functions

    A function without parameter and return value

    A function without parameter and no return value

    A function with parameter and return value

    A function with parameter and no return value

  • 7/29/2019 16066 Functions

    15/67

    A function with no parameter and no return value#include

    void main()

    {clrscr();

    void print(); /*func declarationprint(); /*func callingCout

  • 7/29/2019 16066 Functions

    16/67

    A function with no parameter and no return value

    There is no data transfer between calling and calledfunction

    The function is only executed and nothing is obtained Such functions may be used to print some messages,

    draw stars etc

  • 7/29/2019 16066 Functions

    17/67

    A function with parameter and no return value

    #include

    void main(){

    clrscr();

    int a=10,b=20;

    void mul(int,int);

    mul(a,b); /*actual arguments

    getch();

    }

    void mul(int x, int y) /*formal arguments

    {int s;

    s=x*y;

    Cout

  • 7/29/2019 16066 Functions

    18/67

    A function with parameter and return value#include

    void main()

    {clrscr();

    int a=10,b=20,c;

    int max(int,int);

    c=max(a,b);

    Cout

  • 7/29/2019 16066 Functions

    19/67

    A function without parameter and return value#include

    void main()

    {

    clrscr();

    int a=10,b=20;int sum();

    int c=sum(); /*actual arguments

    Cout

  • 7/29/2019 16066 Functions

    20/67

    Argument passing techniques

    Pass By Value

    Pass By Reference Pass By Pointer\address

  • 7/29/2019 16066 Functions

    21/67

    Call By Value It is a default mechanism for argument passing.

    When an argument is passed by value then the copy ofargument is made know as formal arguments which isstored at separate memory location

    Any changes made in the formal argument are notreflected back to actual argument, rather they remain

    local to the block which are lost once the control isreturned back to calling program

  • 7/29/2019 16066 Functions

    22/67

    Examplevoid main()

    {

    int a=10,b=20;void swap(int,int);

    Cout

  • 7/29/2019 16066 Functions

    23/67

    void swap(int x,int y)

    {

    int z;z=x;

    x=y;

    y=z;

    Cout

  • 7/29/2019 16066 Functions

    24/67

    Output:

    before function calling a=10 b=20

    value of x=20 and y= 10after function calling a=10 b=20

  • 7/29/2019 16066 Functions

    25/67

    Call By pointer/address In this instead of passing value, address are passed.

    Here formal arguments are pointers to the actualarguments

    Hence change made in the argument are permanent.

  • 7/29/2019 16066 Functions

    26/67

    Example

    Void main()

    {

    int a=10 ,b=25;void swap(int *,int *);

    Cout

  • 7/29/2019 16066 Functions

    27/67

    void swap(int *x,int *y)

    {

    int z;z=*x;

    *x=*y;

    *y=z;

    Cout

  • 7/29/2019 16066 Functions

    28/67

    Output:

    before function calling a= 10 b= 25value of x=25 and y=10

    after function calling a=25 b= 10

  • 7/29/2019 16066 Functions

    29/67

    Using Reference Variables

    with Functions To create a second name for a variable in a

    program, you can generate an alias, or an

    alternate name

    In C++ a variable that acts as an alias for another

    variable is called a reference variable, or simply areference

  • 7/29/2019 16066 Functions

    30/67

    Declaring Reference Variables You declare a reference variable by placing a type and

    an ampersand in front of a variable name, as indouble &cash; and assigning another variable of the

    same type to the reference variabledouble someMoney;

    double &cash = someMoney;

    A reference variable refers to the same memoryaddress as does a variable, and a pointer holds thememory address of a variable

  • 7/29/2019 16066 Functions

    31/67

    Pass By Reference

    void main()

    {

    int i=10;int &j=i; // j is a reference variable of I

    cout

  • 7/29/2019 16066 Functions

    32/67

    Output:-Value 10 10

    modified value 20 20

  • 7/29/2019 16066 Functions

    33/67

    #includevoid swap(int &iNum1, int &iNum2);

    void main(){int iVar1, iVar2;cout

  • 7/29/2019 16066 Functions

    34/67

    Declaring Reference Variables There are two differences between reference

    variables and pointers: Pointers are more flexible

    Reference variables are easier to use

    You assign a value to a pointer by inserting anampersand in front of the name of the variablewhose address you want to store in the pointer

    It shows that when you want to use the value storedin the pointer, you must use the asterisk todereference the pointer, or use the value to which itpoints, instead of the address it holds

  • 7/29/2019 16066 Functions

    35/67

    Comparing Pointers and

    References in a Function Header

  • 7/29/2019 16066 Functions

    36/67

    Passing Variable Addresses to Reference

    Variables

    Reference variables are easier to use because you dontneed any extra punctuation to output their values

    You declare a reference variable by placing anampersand in front of the variables name

    You assign a value to a reference variable by usinganother variables name

    The advantage to using reference variables lies increating them in function headers

  • 7/29/2019 16066 Functions

    37/67

    Passing Arrays to Functions An array name actually represents a memory address

    Thus, an array name is a pointer

    The subscript used to access an element of an arrayindicates how much to add to the starting address tolocate a value

    When you pass an array to a function, you are actually

    passing an address

    Any changes made to the array within the functionalso affect the original array

    examp e

  • 7/29/2019 16066 Functions

    38/67

    examp e#include

    void main()

    {void printarr(int [ ]);int a[5];printf(enter the elements of array);for(int i = 0;i

  • 7/29/2019 16066 Functions

    39/67

    Inline Functions Each time you call a function in a C++ program, the

    computer must do the following:

    Remember where to return when the function eventually ends

    Provide memory for the functions variables

    Provide memory for any value returned by the function

    Pass control to the function

    Pass control back to the calling program

    This extra activity constitutes the overhead, or cost ofdoing business, involved in calling a function

  • 7/29/2019 16066 Functions

    40/67

    Using an Inline Function

  • 7/29/2019 16066 Functions

    41/67

    Inline Functions

    An inline function is a small function with no callingoverhead

    Overhead is avoided because program control never

    transfers to the function A copy of the function statements is placed directly

    into the compiled calling program

    The inline function appears prior to the main(),

    which calls it Any inline function must precede any function that

    calls it, which eliminates the need for prototyping inthe calling function

  • 7/29/2019 16066 Functions

    42/67

    Inline Functions

    When you compile a program, the code for the inlinefunction is placed directly within the main() function

    You should use an inline function only in thefollowing situations:

    When you want to group statements together so that you canuse a function name

    When the number of statements is small (one or two lines inthe body of the function)

    When the function is called on few occasions

  • 7/29/2019 16066 Functions

    43/67

    Using Default Arguments

    When you dont provide enough arguments in a functioncall, you usually want the compiler to issue a warningmessage for this error

    Sometimes it is useful to create a function that supplies a

    default value for any missing parameters

  • 7/29/2019 16066 Functions

    44/67

    Using Default Arguments

    Two rules apply to default parameters:

    If you assign a default value to any variable in a function prototypesparameter list, then all parameters to the right of that variable also

    must have default values If you omit any argument when you call a function that has default

    parameters, then you also must leave out all arguments to the rightof that argument

  • 7/29/2019 16066 Functions

    45/67

    Examples of Legal and Illegal

    Use of Functions with Default Parameters

  • 7/29/2019 16066 Functions

    46/67

    Recursion

    When function call itself repeatedly ,until somespecified condition is met then this process is calledrecursion.

    It is useful for writing repetitive problems where eachaction is stated in terms of previous result.

    The need of recursion arises if logic of the problem is

    such that the solution of the problem depends uponthe repetition of certain set of statements withdifferent input values an with a condition.

  • 7/29/2019 16066 Functions

    47/67

    Two basic requirements for recursion :

    1. The function must call itself again and again.2. It must have an exit condition.

  • 7/29/2019 16066 Functions

    48/67

    Factorial using recursion

    void main()

    {

    clrscr();

    int rect(int);

    int n,fact;Coutn;

    fact=rect(n);

    Cout

  • 7/29/2019 16066 Functions

    49/67

    int rect(int a)

    {

    int b;

    if(a==1)

    {

    return(1);

    }

    else

    {

    b=a*rect(a-1);

    return(b);

    }

    }

  • 7/29/2019 16066 Functions

    50/67

    Stack representation

    Rec(3)Rec(3)

    3*Rec(2)

    Rec(3)3*Rec(2)

    3*2*Rec(1).

    .

    Rec(3)

    3*Rec(2)

    3*2*Rec(1)

    3*2*1

  • 7/29/2019 16066 Functions

    51/67

    Advantages of recursion1. It make program code compact which is easier towrite and understand.

    2. It is used with the data structures such aslinklist,stack,queues etc.

    3. It is useful if a solution to a problem is in repetitiveform.

    4. The compact code in a recursion simplifies thecompilation as less number of lines need to be

    compiled.

  • 7/29/2019 16066 Functions

    52/67

    Disadvantages

    1. Consume more storage space as recursion calls andautomatic variables are stored in a stack.

    2. It is less efficient in comparison to normal programin case of speed and execution time

    3. Special care need to be taken for stopping conditionin a recursion function

    4. If the recursion calls are not checked ,the computermay run out of memory.

  • 7/29/2019 16066 Functions

    53/67

    Pointer to Function Function pointers are pointers, i.e. variables, whichpoint to the address of a function.

    The syntax to declare to declare a function pointer is as

    follows:[return_type] (*pointer_name)[(list_of_parameters)]

    example:

    Function declaration int add(int ,int);

    Pointer declaration int(*ptr)(int,int);Assigning address of the function to pointer

    ptr=add;

  • 7/29/2019 16066 Functions

    54/67

    Example#include

    #include

    Void main()

    {

    clrscr();int x=3,y=5,z;

    int add(int , int);

    int (*ptr)(int,int);

    ptr=add;z=(*ptr)(x,y);

    Cout

  • 7/29/2019 16066 Functions

    55/67

    Contd

    int add(int x,int y)

    {

    return(x+y);

    }

  • 7/29/2019 16066 Functions

    56/67

  • 7/29/2019 16066 Functions

    57/67

    Polymorphism

    The word polymorphism is derived from Greek wordPoly which means many and morphos which means

    forms.

    Polymorphism can be defined as the ability to use thesame name for two or more related but technicallydifferent tasks.

    Eg-woman plays role of daughter,sister,wife,motheretc.

  • 7/29/2019 16066 Functions

    58/67

    Overloading in C++What is overloading

    Overloading means assigning multiple

    meanings to a function name or operator

    symbol

    It allows multiple definitions of a function with thesame name, but different signatures.

    C++ supports Function overloading

    Operator overloading

  • 7/29/2019 16066 Functions

    59/67

    Why is Overloading Useful? Function overloading allows functions thatconceptually perform the same task on

    objects of different types to be given the

    same name.

    Operator overloading provides a convenient

    notation for manipulating user-defined

    objects with conventional operators.

  • 7/29/2019 16066 Functions

    60/67

    Function Overloading

    Is the process of using the same name for two or morefunctions

    Requires each redefinition of a function to use adifferent function signature that is:

    different types of parameters,

    or sequence of parameters, or number of parameters

    Is used so that a programmer does not have toremember multiple function names

  • 7/29/2019 16066 Functions

    61/67

  • 7/29/2019 16066 Functions

    62/67

    Function Overloading Two or more functions can have the same name but

    different parameters

    Example:int max(int a, int b){

    if (a>= b)return a;

    elsereturn b;

    }

    float max(float a, float b){

    if (a>= b)return a;

    elsereturn b;

    }

  • 7/29/2019 16066 Functions

    63/67

    Overloading Function Call

    Resolution Overloaded function call resolution is done by

    compiler during compilation

    The function signature determines which definition

    is used

    a Function signature consists of:

    Parameter types and number of parameters

    supplied to a function a Function return type is not part of function signature

    and is not used in function call resolution

    E l

  • 7/29/2019 16066 Functions

    64/67

    ExampleVoid sum(int,int);

    Void sum(double,double);Void sum(char,char);

    Void main()

    {

    int a=10,b=20 ;

    double c=7.52,d=8.14;

    char e=a , f=b ;

    sum(a,b);sum(c,d);

    sum(e,f);

    }

    C d

  • 7/29/2019 16066 Functions

    65/67

    Contd..Void sum(int x,int y)

    {Cout

  • 7/29/2019 16066 Functions

    66/67

    Output:

    Sum of integers 30

    sum of two floating no are 15.66

    sum of characters are 195

  • 7/29/2019 16066 Functions

    67/67