Ch05 Functions

  • Upload
    nidamah

  • View
    243

  • Download
    0

Embed Size (px)

Citation preview

  • 8/10/2019 Ch05 Functions

    1/24

    Introduction to Programming

    Engr. Rashid Farid Chishti

    [email protected]

    Chapter 05: Functions

    International Islamic University H-10, Islamabad, Pakistan

    http://www.iiu.edu.pk

    mailto:[email protected]:[email protected]
  • 8/10/2019 Ch05 Functions

    2/24

    FunctionsA functiongroups a number of program

    statements into a unit and gives it a name. This unit can then be invokedfrom other parts

    of the program.

    The most important reason to use functions is

    to aid in the conceptual organizationof a

    program

    Another reason to use functions is to reduce

    program size. Any sequence of instructions

    that appears in a program more than once is a

    candidate for being made into a function. The functions code is stored in only one

    placein memory, even though the function is

    executed many timesin the course of the

    program.

  • 8/10/2019 Ch05 Functions

    3/24

    Return type

    Input arguments

  • 8/10/2019 Ch05 Functions

    4/24

    Functions//demonstrates a simple function

    #includeusingnamespacestd;

    intcube(intx); // function deration

    intmain(){ // tests the cube() function:

    intn = 1;

    while(n != 0){cin >> n;

    cout

  • 8/10/2019 Ch05 Functions

    5/24

    Functions

    Each integer read is passed to the cube()function by the

    call cube(n). The value returnedby the function replaces

    the expression cube(n) and then is passed to the output

    object cout

    Themain()function passes the value 5 to the cube()

    function, and the cube()function returns the value125

    to themain()function.

    The argument nispassed by valueto the formalparameter

    x. This simply means that x is assigned the value of n

    when the function is called.

  • 8/10/2019 Ch05 Functions

    6/24

    Two Argument Functions//Calculates max of two Numbers

    #includeusingnamespacestd;

    intmax(int, int); // function deration

    intmain(){ // tests the max() function:

    intm = 1, n;

    while( m != 0){cin >> m >> n;

    cout

  • 8/10/2019 Ch05 Functions

    7/24

    Writing function before main// Calculates Factorial

    #include#include

    usingnamespacestd;

    longfact(intn){ // returns n! = n*(n-1)*(n-2)*...*(2)(1)

    if(n < 0) return0;

    intf = 1;while(n > 1)

    f *= n--; // first f=f*n then n decrements

    returnf;

    }

    intmain(){ // tests the factorial() function:for(int i=-1; i < 6; i++)

    cout

  • 8/10/2019 Ch05 Functions

    8/24

    Calculating Permutations

    // Calculates Permutation using Factorial

    #include

    #include

    usingnamespacestd;longfact(intn){ // returns n! = n*(n-1)*(n-2)*...*(2)(1)

    if(n < 0) return0;

    intf = 1;

    while(n > 1)

    f *= n--; // first f=f*n then n decrementsreturnf;

    }

    longperm(intn, intk){ // returns n Permutation k

    if( n

  • 8/10/2019 Ch05 Functions

    9/24

  • 8/10/2019 Ch05 Functions

    10/24

    Passing by Value and Passing by Reference

    #include

    #include

    usingnamespacestd;

    voidf(intx, int&y){ // changes reference argument to 99:

    x = 88;

    y = 99;

    }intmain(){ // tests the f() function:

    inta = 22,b = 44;

    cout

  • 8/10/2019 Ch05 Functions

    11/24

    Passing by Value and Passing by Reference

    #include

    #include

    usingnamespacestd;

    voidswap(float&x, float&y){ // exchanges value of x and y

    floattemp = x;

    x = y;

    y = temp;}

    intmain(){ // tests the swap() function:

    floata = 22.2, b = 44.5;

    cout

  • 8/10/2019 Ch05 Functions

    12/24

    Returning More than One Value

    #include

    #include

    usingnamespacestd;

    voidcomputeCircle( double&, double&, constdouble& );

    intmain(){ // tests the computeCircle() function:

    doubler,a,c; cout > r;

    computeCircle(a, c, r);

    cout

  • 8/10/2019 Ch05 Functions

    13/24

    Local and Global Variables

    #include

    #include

    usingnamespacestd;

    intx = 10; // a global variable x

    intmain(){

    intx = 50; // local variable x

    cout

  • 8/10/2019 Ch05 Functions

    14/24

    Default Arguments

    #include

    #include

    usingnamespacestd;

    //declaration with default arguments

    voidrepchar(char='*', int=45);

    intmain(){

    repchar(); //prints 45 asterisks

    repchar('='); //prints 45 equal signs

    repchar('+', 30); //prints 30 plus signs

    system("PAUSE"); return0;

    }

    voidrepchar(charch, intn){// displays line of characters

    // defaults supplied if necessary

    for(int j=0; j

  • 8/10/2019 Ch05 Functions

    15/24

    Inline Function

    A function call involves substantial overhead.

    Extra time and space have to be used to invoke

    the function, pass parameters to it, allocate

    storage for its local variables, store the

    current variables and the location of execution

    in the main program, etc.

    In some cases, it is better to avoid all thisby specifying the function to be inline. This

    tells the compiler to replace each call to the

    function with explicit code for the function.

    To the programmer, an inline function appears

    the same as an ordinary function, except for

    the use of the inlinespecifier.

  • 8/10/2019 Ch05 Functions

    16/24

    Inline Function

    // demonstrates inline functions

    #include

    #include

    usingnamespacestd;

    inlinefloatlbstokg(floatpounds){

    // converts pounds to kilograms

    return0.453592 * pounds;

    }

    intmain(){

    floatlbs;

    cout > lbs;

    cout

  • 8/10/2019 Ch05 Functions

    17/24

    Function Overloading

    // Calculates Factorial

    #include

    #include

    usingnamespacestd;

    intadd(inta, intb){

    cout

  • 8/10/2019 Ch05 Functions

    18/24

    Recursion

    The existence of functions makes possible a

    programming technique called recursion. Recursion involves a function calling

    itself. This sounds rather improbable, and

    indeed a function calling itself is often a

    bug. However, when used correctly thistechnique can be surprisingly powerful.

    Recursion is much easier to understand with

    an example than with lengthy explanations,

    so lets apply it to a program weve seen

    before:

    The next program, uses recursion instead of

    a loop to calculate factorial.

  • 8/10/2019 Ch05 Functions

    19/24

    Recursion

    #include

    #include

    usingnamespacestd;

    // calls itself to calculate factorials

    unsignedlongfct(unsigned long n){

    staticintI = 0; I++;

    cout

  • 8/10/2019 Ch05 Functions

    20/24

    Recursion

  • 8/10/2019 Ch05 Functions

    21/24

    Returning by Reference

    Besides passing values by reference, you can also

    return a value by reference.

    The reason is to allow you to use a function call on

    the left side of the equal sign.

    variable returned by the function is assigned the

    value on the right side of the equal sign.

    You cant return a constant from a function that

    returns by reference.

    int& seta(){

    return 3; // Error

    }

    You cant return a reference to a local variable:int& seta(){

    int x = 3;

    return x; // error

    }

  • 8/10/2019 Ch05 Functions

    22/24

    Returning by Reference

    #include

    #include

    usingnamespacestd;

    inta = 10;

    int& seta(){ // return type is int&

    returna; //only global var can be returned by reference

    }

    intmain(){

    cout

  • 8/10/2019 Ch05 Functions

    23/24

    Assignment #31. Implement the permutation

    through perm() function2. Write a function that returns GCD(Greatest

    Common Divisor) of two Numbers.

    3. Write a function that returns LCM(LeastCommon Multiple) of two Numbers.

    4. Write a recursive functionpower( base,exponent ), when invoked, returnsbaseexponent.

    For example, power( 3, 4 ) = 3 * 3 * 3 * 3.Assume that exponent is an integer greaterthan or equal to 1. Hint: The recursion step

    would use the relationshipbaseexponent=basebase(exponent 1)

    and the terminating condition occurs whenexponent is equal to 1, becausebase1= base.

    )!(!

    !

    rnr

    nC

    r

    n

  • 8/10/2019 Ch05 Functions

    24/24

    Assignment #31. Write a function to determine the prime

    factors of a number by defining the functionPfactors

    e.g., prime factors of 24 are 2,2,2,3 and

    35 are 5,7

    Display the result in the function.