introduction to computing lec 5

Upload: subhabrata-das

Post on 03-Jun-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 introduction to computing lec 5

    1/68

    Functions, Library Function,

    Recursive Functionsubhabrata dasassam engineeirng college

    lecture 5

  • 8/12/2019 introduction to computing lec 5

    2/68

    Program Modules in C

    Functions Modules in C Programs combine user-defined functions with library functions

    C standard library has a wide variety of functions

    Function calls

    Invoking functions Provide function name and arguments (data)

    Function performs operations or manipulations

    Function returns results

    Function call analogy: Boss asks worker to complete task

    Worker gets information, does task, returns result

    Information hiding: boss does not know details

  • 8/12/2019 introduction to computing lec 5

    3/68

    Note

    Using the functions in the C Standard Libraryhelps make programs more portable.

  • 8/12/2019 introduction to computing lec 5

    4/68

    Math Library Functions

    Math library functions perform common mathematical calculations #include

    Format for calling functions FunctionName( argument);

    If multiple arguments, use comma-separated list

    printf( "%.2f", sqrt( 900.0 ) ); Callsfunction sqrt, which returns the square root of its

    argument

    All math functions return data type double

    Arguments may be constants, variables, orexpressions

  • 8/12/2019 introduction to computing lec 5

    5/68

    Note:

    Include the math header by using thepreprocessor directive #includewhen using functions in the math library.

  • 8/12/2019 introduction to computing lec 5

    6/68

    Function Description Example

    sqrt( x ) square root of x sqrt( 900.0)is30.0sqrt( 9.0)is3.0

    exp( x ) exponential function ex exp( 1.0)is2.718282exp( 2.0) s 7.389056

    log( x ) natural logarithm of x(basee)

    log( 2.718282)is1.0log(7.389056)is2.0

    log10( x ) logarithm of x(base 10) log10(1.0)is 0.0log10( 10.0 )is 1.0log10( 100.0)is2.0

    fabs( x ) absolute value of x fabs( 5.0)is5.0fabs( 0.0)is0.0fabs( -5.0)is5.0

    ceil( x ) rounds xto the smallestinteger not less than x

    ceil( 9.2)is 10.0ceil( -9.8)is-9.0

    Commonly used math library functions.

  • 8/12/2019 introduction to computing lec 5

    7/68

    Function Description Example

    floor( x ) roundsxto the largest integernot greater thanx

    floor(9.2)is 9.0floor(-9.8)is-10.0

    pow( x, y ) xraised to powery(xy) pow( 2, 7)is 128.0pow( 9, .5)is3.0

    fmod( x, y ) remainder ofx/yas a floating-point number

    fmod( 13.657,2.333)is1.992

    sin( x ) trigonometric sine ofx(xin radians)

    sin( 0.0)is0.0

    cos( x ) trigonometric cosine ofx(x in radians)

    cos( 0.0)is1.0

    tan( x ) trigonometric tangent ofx(x in radians)

    tan( 0.0)is0.0

    Commonly used math library functions.

  • 8/12/2019 introduction to computing lec 5

    8/68

    Standard library header Explanation

    Contains macros and information for adding diagnostics thataid program debugging.

    Contains function prototypes for functions that test charactersfor certain properties, and function prototypes for functions

    that can be used to convert lowercase letters to uppercase

    letters and vice versa.

    Defines macros that are useful for reporting error conditions. Contains the floating-point size limits of the system. Contains the integral size limits of the system. Contains function prototypes and other information that

    enables a program to be modified for the current locale on

    which it is running. The notion of locale enables the computer

    system to handle different conventions for expressing data like

    dates, times, dollar amounts and large numbers throughout

    the world.

    Some of the standard library headers.

  • 8/12/2019 introduction to computing lec 5

    9/68

    Standard library header Explanation

    Contains function prototypes for math library functions. Contains function prototypes for functions that allow bypassing of

    the usual function call and return sequence.

    Contains function prototypes and macros to handle variousconditions that may arise during program execution.

    Defines macros for dealing with a list of arguments to a functionwhose number and types are unknown.

    Contains common definitions of types used by C for performingcertain calculations.

    Some of the standard library headers.

  • 8/12/2019 introduction to computing lec 5

    10/68

    Standard library header Explanation

    Contains function prototypes for the standard input/outputlibrary functions, and information used by them.

    Contains function prototypes for conversions of numbers totext and text to numbers, memory allocation, random

    numbers, and other utility functions.

    Contains function prototypes for string-processing functions. Contains function prototypes and types for manipulating the

    time and date.

    Some of the standard library headers.

  • 8/12/2019 introduction to computing lec 5

    11/68

    Functions

    Functions Modularize a program

    All variables defined inside functions are local variables Known only in function defined

    Parameters

    Communicate information between functions Local variables

    Benefits of functions Divide and conquer

    Manageable program development

    Software reusability Use existing functions as building blocks for new programs

    Abstraction - hide internal details (library functions)

    Avoid code repetition

  • 8/12/2019 introduction to computing lec 5

    12/68

    Function Characteristics

    Basically a function has the following characteristics:

    1. Named with unique name.

    2. Performs a specific task- Task is a discrete job that the programmust perform as part of its overall operation, such as sending a

    line of text to the printer, sorting an array into numerical order, orcalculating a cube root, etc.

    3. Independent- A function can perform its task without interferencefrom or interfering with other parts of the program.

    4. May receive values from the calling program (caller)- Calling

    program can pass values to function for processing whetherdirectly or indirectly (by reference).

    5. May return a value to the calling programthe called functionmay pass something back to the calling program.

  • 8/12/2019 introduction to computing lec 5

    13/68

    Function Mechanism

    C program does not execute the statements in afunction until the function is called.

    When it is called, the program can send

    information to the function in the form of one ormore arguments although it is not a mandatory.

    Argument is a program data needed by thefunction to perform its task.

    When the function finished processing, programreturns to the same location which called thefunction.

  • 8/12/2019 introduction to computing lec 5

    14/68

    Parts of a Function

    C Function has got two parts:

    Function Header

    Function Definition

  • 8/12/2019 introduction to computing lec 5

    15/68

    The first line of every function definition is called function header. It has 3

    components, as shown below,

    The Function header

    1. Function return type - Specifies the data type that the function should returns to

    the caller program. Can be any of C data types: char, float, int, long,double, pointers etc. If there is no return value, specify a return type of

    void. For example,

    int calculate_yield() // returns an int type

    float mark() // returns a float type

    void calculate_interest() // returns nothing

    C FUNCTIONS

  • 8/12/2019 introduction to computing lec 5

    16/68

    1. Function name- Can have any name as long as the

    rules for C / C++ variable names are followed and

    must be unique.

    2. Parameter list- Many functions use arguments, thevalue passed to the function when it is called. A

    function needs to know the data type of

    each argument. Argument type is provided in the

    function header by the parameter list. Parameter listacts as a placeholder.

    C FUNCTIONS

  • 8/12/2019 introduction to computing lec 5

    17/68

    For each argument that is passed to the function, the

    parameter list must contain one entry, which specifies thetype and the name.

    For example,

    void myfunction(int x, float y, char z)

    void yourfunction(float myfloat, char mychar)

    int ourfunction(long size)

    The first line specifies a function with three arguments: type

    intnamed x, type floatnamed yand type charnamed

    z.

    Some functions take no arguments, so the parameter list

    should be voidor empty such as,

    long thefunction(void)

    void testfunct(void)

    int zerofunct()

    C FUNCTIONS

  • 8/12/2019 introduction to computing lec 5

    18/68

    Parameter is an entry in a function header. It serves as a placeholder

    for an argument. It is fixed, that is, do not change during execution.

    The argument is an actual value passed to the function by the caller

    program. Each time a function is called, it can be passed with

    different arguments.

    A function must be passed with the same number and type of

    arguments each time it is called, but the argument values can be

    different.

    See program in the

    next slide

    C FUNCTIONS

  • 8/12/2019 introduction to computing lec 5

    19/68

    Example : parameter & argument

    #include

    float half_of(float); /*prototype*/

    int main(){

    float z,x=3.5,y=65.11;

    printf(The function call statement is z=half_of(x)\n);

    printf(where x = 3.5 and y = 65.11\n);

    printf(Passing the argument x\n);

    z=half_of(x);

    printf(The value of z = %f\n,z);

    printf(Passing the argument y\n);

    z=half_of(y);

    printf(The value of z = %f\n,z);return 0;

    }

    float half_of(float k){

    return (k/2.0);

    }

  • 8/12/2019 introduction to computing lec 5

    20/68

    For the first function call:

    Then, the second function call:

    Each time a function is called, the different arguments are passed to the

    functions parameter.

    z = half_of(y)and z = half_of(x), each send a different

    argument to half_of()through the kparameter.

    The first call send x, which is 3.5, then the second call send y, which is

    65.11. The value of xand yare passed (copied) into the parameter kof

    half_of().

    Same effect as copying the values from xto k, and then yto k.

    half_of()then returns this value after dividing it by 2.

    C FUNCTIONS

  • 8/12/2019 introduction to computing lec 5

    21/68

    Enclosed in curly braces, immediately follows the function header.

    Real work in the program is done here.

    When a function is called execution begins at the start of the function

    body and terminates (returns to the calling program) when a return

    statement is encountered or when execution reaches the closing braces

    (}). Variable declaration can be made within the body of a function.

    Which are called local variables. The scope, that is the visibility and

    validity of the variables are local.

    Local variables are the variables apply only to that particular function,

    are distinct from other variables of the same name (if any) declaredelsewhere in the program outside the function.

    It is declared, initialized and use like any other variable.

    Outside of any functions, those variables are called global variables.

    The Function BodyC FUNCTIONS

  • 8/12/2019 introduction to computing lec 5

    22/68

    See program next slide

    The function parameters are considered to be variable declarations.

    Function prototype normally placed before main()and your function

    definition after main()as shown below. For C++, the standard said that we must include the prototype but not

    for C.

    C FUNCTIONS

    http://localhost/var/www/apps/conversion/tmp/scratch_5/cfunctions/functiongloballocalvariable.txthttp://localhost/var/www/apps/conversion/tmp/scratch_5/cfunctions/functiongloballocalvariable.txt
  • 8/12/2019 introduction to computing lec 5

    23/68

    Global & Local Variables

    #include

    void demo(); /*prototype*/

    int globalVar ; /*global variable*/

    int main(){

    int x=1,y=2; /*local variables*/

    globalVar = 8; /*sets global variables*/

    printf(globalVar in (main())= %d\n,globalVar);

    printf(Before calling function demo(), x = %d and y = %d\n,x,y);

    demo();

    printf(After calling function demo(), x = %d and y = %d\n,x,y);

    return 0;

    }

    void demo(){

    int x = 88, y=99; /*local variables*/

    printf(globalVar in ( demo()) = %d\n, ++globalVar);

    printf(Within demo(), x = %d and y = %d \n, x,y);

    }

  • 8/12/2019 introduction to computing lec 5

    24/68

    #include

    /* function prototype

    */

    int funct1(int);

    int main()

    {

    /* function call

    */

    int y =

    funct1(3);

    }

    /* Function

    definition */

    int funct1(int x)

    {}

    But it is OK if we directly declare and define the function

    before main()as shown below.#include

    /* declare and define */

    int funct1(int x)

    {

    }

    int main()

    {

    /* function call */

    int y = funct1(3);

    }

    Three rules govern the use of variables in functions:

    1. To use a variable in a function, we must declare it in the function header or the

    function body.

    2. For a function to obtain a value from the calling program (caller), the value must be

    passed as an argument (the actual value).

    3. For a calling program (caller) to obtain a value from function, the value must be

    explicitly returned from the called function (callee).

    C FUNCTIONS

  • 8/12/2019 introduction to computing lec 5

    25/68

    A function may or may not return a value.

    If function does not return a value, then the function return type is said to be of

    type void.

    To return a value from a function, use returnkeyword, followed by C

    expression.

    The value is passed back to the caller. The return value must match the return data type.

    A function can contain multiple return statements.

    The Function Statements

    Any statements can be included within a function, however a function may notcontain the definition of another function.

    For examples: if statements, loop, assignments etc are valid statements.

    Returning a Value

    See Program example next slide : multiple return statement

    C FUNCTIONS

    http://localhost/var/www/apps/conversion/tmp/scratch_5/cfunctions/functionmultiplereturn.txthttp://localhost/var/www/apps/conversion/tmp/scratch_5/cfunctions/functionmultiplereturn.txthttp://localhost/var/www/apps/conversion/tmp/scratch_5/cfunctions/functionmultiplereturn.txt
  • 8/12/2019 introduction to computing lec 5

    26/68

    Function with multiple return

    #include

    int Max(int, int); /*prototype*/

    int main(){

    int x,y; /*local variables*/

    printf(Enter two different integer values,\n);

    printf(separated by space. Then press Enter key.\n);scanf(%d %d, &x, &y);

    printf(The larger value is %d \n, Max(x,y));

    return 0;

    }

    int max( int x, int y){if (x>= y) return x;

    else return y;

    }

  • 8/12/2019 introduction to computing lec 5

    27/68

    Must be included for each function that will be defined, (required by

    Standards for C++ but optional for C) if not directly defined before

    main().

    In most cases it is recommended to include a function prototype in your

    C program to avoid ambiguity.

    Identical to the function header, with semicolon (;) added at the end.

    Function prototype includes information about the functions return

    type, name and parameters list and type.

    The general form of the function prototype is shown below,

    function_return_type function_name(type parameter1, type parameter2,,type parameterN)

    An example of function prototype,

    long cube(long);

    The Function Prototype

    C FUNCTIONS

    C C O S

  • 8/12/2019 introduction to computing lec 5

    28/68

    Function prototype provides the C compiler the name and arguments of the

    functions and must appear before the function is used or defined. It is a model for a function that will appear later, somewhere in the program.

    From the previous prototype example, 'we' know the function is named

    cube, it requires a variable of the type long, and it will return a value of

    type long.

    Then, the compiler can check every time the source code calls the function,verify that the correct number and type of arguments are being passed to the

    function and check that the return value is returned correctly.

    If mismatch occurs, the compiler generates an error message enabling

    programmers to trap errors.

    A function prototype need not exactly match the function header.

    The optional parameter names can be different, as long as they are the same

    data type, number and in the same order.

    But, having the name identical for prototype and the function header makes

    source code easier to understand.

    C FUNCTIONS

    C FUNCTIONS

  • 8/12/2019 introduction to computing lec 5

    29/68

    Normally placed before the start of main()but must be

    before the function definition.

    Provides the compiler with the description of a function

    that will be defined at a later point in the program.

    Includes a return type which indicates the type of variable

    that the function will return. And function name, which normally describes what the

    function does.

    Also contains the variable types of the arguments that will

    be passed to the function. Optionally, it can contain the names of the variables that

    will be returned by the function.

    A prototype should always end with a semicolon ( ;).

    C FUNCTIONS

    1 /* Fig. 5.3: fig05_03.c

  • 8/12/2019 introduction to computing lec 5

    30/68

    2 Creating and using a programmer-defined function */3 #include4

    5 intsquare( inty ); /* function prototype */6

    7 /* function main begins program execution */8 intmain( void)9 {10 intx; /* counter */11

    12 /* loop 10 times and calculate and output square of x each time */13 for( x = 1; x

  • 8/12/2019 introduction to computing lec 5

    31/68

    Note: Common Programming Error

    Returning a value from a function with avoid return type is a syntaxerror.

  • 8/12/2019 introduction to computing lec 5

    32/68

    Good Programming Practice

    Choosing meaningful function names andmeaningful parameter names makesprograms more readable and helps avoid

    excessive use of comments.

    1 /* Fig. 5.4: fig05_04.c

  • 8/12/2019 introduction to computing lec 5

    33/68

    33

    2 Finding the maximum of three integers */3 #include4

    5 intmaximum( intx, inty, intz );/* function prototype */6

    7 /* function main begins program execution */8 intmain( void)9 {10 intnumber1; /* first integer */11 intnumber2; /* second integer */12 intnumber3; /* third integer */13

    14 printf( "Enter three integers: ");15 scanf( "%d%d%d", &number1, &number2, &number3 );16

    17 /* number1, number2 and number3 are arguments18 to the maximum function call */19 printf( "Maximum is: %d\n", maximum( number1, number2, number3 ) );20

    21 return0; /* indicates successful termination */22

    23 } /* end main */24

    Function

    prototype

    Function

    call

    25 /* Function maximum definition */

  • 8/12/2019 introduction to computing lec 5

    34/68

    34

    26 /* x, y and z are parameters */27 intmaximum( intx, inty, intz )28 {29 intmax = x; /* assume x is largest */30

    31 if( y > max ) { /* if y is larger than max, assign y to max */32 max = y;33 } /* end if */34

    35 if( z > max ) { /* if z is larger than max, assign z to max */36 max = z;37 } /* end if */38

    39 returnmax; /* max is largest value */40

    41 } /* end function maximum */Enter three integers: 22 85 17Maximum is: 85

    Enter three integers: 85 22 17Maximum is: 85

    Enter three integers: 22 17 85Maximum is: 85

    Function

    definition

  • 8/12/2019 introduction to computing lec 5

    35/68

    Good Programming Practice

    Includefunctionprototypesfor all functions totake advantage of Cs type-checkingcapabilities. Use #includepreprocessordirectives to obtain function prototypes forthe standard library functions from theheaders for the appropriate libraries, or toobtain headers containing function prototypes

    for functions developed by you.

  • 8/12/2019 introduction to computing lec 5

    36/68

    Common Programming Error

    Forgetting the semicolon at the end of afunction prototype is a syntax error.

  • 8/12/2019 introduction to computing lec 5

    37/68

    Calling Functions: Call-by-Value and Call-by-

    Reference

    Call by value

    Copy of argument passed to function

    Changes in function do not effect original

    Use when function does not need to modify argument Avoids accidental changes

    Call by reference

    Passes original argument

    Changes in function effect original Only used with trusted functions

    For now, we focus on call by value

  • 8/12/2019 introduction to computing lec 5

    38/68

    Random Number Generation randfunction

    Load

    Returns "random" number between 0and RAND_MAX(at least 32767) i = rand();

    Pseudorandom

    Preset sequence of "random" numbers

    Same sequence for every function call

    Scaling

    To get a random number between 1and n 1 + ( rand() % n )

    rand() % nreturns a number between 0 and n - 1

    Add 1to make random number between 1 and n

    1 + ( rand() % 6) Is a number between 1and 6

    1 /* Fig. 5.7: fig05_07.c2

  • 8/12/2019 introduction to computing lec 5

    39/68

    39

    2 Shifted, scaled integers produced by 1 + rand() % 6 */3 #include4 #include5

    6 /* function main begins program execution */7 intmain( void)8 {9 inti; /* counter */10

    11 /* loop 20 times */12 for( i = 1; i

  • 8/12/2019 introduction to computing lec 5

    40/68

    40

    2 Roll a six-sided die 6000 times */3 #include4 #include5

    6 /* function main begins program execution */7 intmain( void)8 {9 intfrequency1 = 0; /* rolled 1 counter */10 intfrequency2 = 0; /* rolled 2 counter */11 intfrequency3 = 0; /* rolled 3 counter */12 intfrequency4 = 0; /* rolled 4 counter */13 intfrequency5 = 0; /* rolled 5 counter */14 intfrequency6 = 0; /* rolled 6 counter */15

    16 introll; /* roll counter, value 1 to 6000 */17 intface; /* represents one roll of the die, value 1 to 6 */18

    19 /* loop 6000 times and summarize results */20 for( roll = 1; roll

  • 8/12/2019 introduction to computing lec 5

    41/68

    41

    31 ++frequency2;32 break;33

    34 case3: /* rolled 3 */35 ++frequency3;36 break;37

    38 case4: /* rolled 4 */39 ++frequency4;40 break;41

    42 case5: /* rolled 5 */43 ++frequency5;44 break;45

    46 case6: /* rolled 6 */47 ++frequency6;48 break; /* optional */49 } /* end switch */50

    51 } /* end for */52

    53 /* display results in tabular format */

  • 8/12/2019 introduction to computing lec 5

    42/68

    42

    54 printf( "%s%13s\n", "Face", "Frequency");55 printf( " 1%13d\n", frequency1 );56 printf( " 2%13d\n", frequency2 );57 printf( " 3%13d\n", frequency3 );58 printf( " 4%13d\n", frequency4 );59 printf( " 5%13d\n", frequency5 );60 printf( " 6%13d\n", frequency6 );61

    62 return0; /* indicates successful termination */63

    64 } /* end main */Face Frequency

    1 10032 10173 9834 9945 10046 999

  • 8/12/2019 introduction to computing lec 5

    43/68

    Random Number Generation

    srand function

    Takes an integer seed and jumps to that location

    in its "random" sequencesrand(seed );

    srand( time( NULL ) );/*load */

    time( NULL ) Returns the number of seconds that have passed since

    January 1, 1970

    Randomizes" the seed

    1 /* Fig. 5.9: fig05_09.c

  • 8/12/2019 introduction to computing lec 5

    44/68

    2 Randomizing die-rolling program */3 #include4 #include5

    6 /* function main begins program execution */7 intmain( void)8 {9 inti; /* counter */10 unsignedseed; /* number used to seed random number generator */11

    12 printf( "Enter seed: ");13 scanf( "%u", &seed ); /* note %u for unsigned */14

    15 srand( seed ); /* seed random number generator */16

    17 /* loop 10 times */18 for( i = 1; i

  • 8/12/2019 introduction to computing lec 5

    45/68

    45

    21 printf( %10d , 1+ ( rand() % 6) );22

    23 /* if counter is divisible by 5, begin a new line of output */24 if( i % 5== 0) {25 printf( \n );26 } /* end if */27

    28 } /* end for */29

    30 return0; /* indicates successful termination */31

    32} /* end main */Enter seed: 676 1 4 6 21 6 1 6 4

    Enter seed: 8672 4 6 1 61 1 3 6 2

    Enter seed: 676 1 4 6 21 6 1 6 4

  • 8/12/2019 introduction to computing lec 5

    46/68

    Exercise:

    Write down a function which generate the

    sum of two dies, print the value of each

    die generated and sum, then return sum.

    78

  • 8/12/2019 introduction to computing lec 5

    47/68

    47

    79 /* roll dice, calculate sum and display results */80 introllDice( void)81 {82 intdie1; /* first die */83 intdie2; /* second die */84 intworkSum; /* sum of dice */85

    86 die1 = 1+ ( rand() % 6); /* pick random die1 value */87 die2 = 1+ ( rand() % 6); /* pick random die2 value */88 workSum = die1 + die2; /* sum die1 and die2 */89

    90 /* display results of this roll */91 printf( Player rolled %d + %d = %d\n , die1, die2, workSum );92

    93 returnworkSum; /* return sum of dice */94

    95 } /* end function rollRice */

  • 8/12/2019 introduction to computing lec 5

    48/68

    Storage Classes

    Storage class specifiers

    Storage durationhow long an object exists in memory

    Scopewhere object can be referenced in program

    Linkagespecifies the files in which an identifier is known (more in

    Later on )

    Automatic storage

    Object created and destroyed within its block

    auto:default for local variables

    auto double x, y;

    register:tries to put variable into high-speed registers

    Can only be used for automatic variables

    register int counter = 1;

  • 8/12/2019 introduction to computing lec 5

    49/68

    Note:

    Automatic storage is a means of conservingmemory, because automatic variables existonly when they are needed. They are

    created when the function in which theyare defined is entered and they aredestroyed when the function is exited.

    1 /* Fig. 5.12: fig05_12.c

  • 8/12/2019 introduction to computing lec 5

    50/68

    50

    2 A scoping example */3 #include4

    5 voiduseLocal( void); /* function prototype */6 voiduseStaticLocal( void); /* function prototype */7 voiduseGlobal( void); /* function prototype */8

    9 intx = 1; /* global variable */10

    11 /* function main begins program execution */12 intmain( void)13 {14 intx = 5; /* local variable to main */15

    16 printf("local x in outer scope of main is %d\n", x );17

    18 { /* start new scope */19 intx = 7; /* local variable to new scope */20

    21 printf( "local x in inner scope of main is %d\n", x );22 } /* end new scope */23

    Global variable with file scope

    Variable with block scope

    Variable with block

    scope

    24 printf( local x in outer scope of main is %d\n , x );25

  • 8/12/2019 introduction to computing lec 5

    51/68

    51

    25

    26 useLocal(); /* useLocal has automatic local x */27 useStaticLocal(); /* useStaticLocal has static local x */28 useGlobal(); /* useGlobal uses global x */29 useLocal(); /* useLocal reinitializes automatic local x */30 useStaticLocal(); /* static local x retains its prior value */31 useGlobal(); /* global x also retains its value */32

    33 printf( \nlocal x in main is %d\n , x );34

    35 return0; /* indicates successful termination */3637 } /* end main */38

    39 /* useLocal reinitializes local variable x during each call */40 voiduseLocal( void)41 {42 intx = 25; /* initialized each time useLocal is called */43

    44 printf( \nlocal x in useLocal is %d after entering useLocal\n , x );45 x++;46 printf( local x in useLocal is %d before exiting useLocal\n , x );47 } /* end function useLocal */48

    Variable with block

    scope

    49 /* useStaticLocal initializes static local variable x only the first time

  • 8/12/2019 introduction to computing lec 5

    52/68

    52

    50 the function is called; value of x is saved between calls to this51 function */52 voiduseStaticLocal( void)53 {54 /* initialized only first time useStaticLocal is called */55 static intx = 50;56

    57 printf( "\nlocal static x is %d on entering useStaticLocal\n", x );58 x++;59 printf( "local static x is %d on exiting useStaticLocal\n", x );60 } /* end function useStaticLocal */61

    62 /* function useGlobal modifies global variable x during each call */63 voiduseGlobal( void )64 {65 printf( "\nglobal x is %d on entering useGlobal\n", x );66 x *= 10;67 printf( "global x is %d on exiting useGlobal\n", x );68 } /* end function useGlobal */

    Static variable with block scope

    Global variable

    local x in outer scope of main is 5

  • 8/12/2019 introduction to computing lec 5

    53/68

    local x in inner scope of main is 7local x in outer scope of main is 5local x in useLocal is 25 after entering useLocallocal x in useLocal is 26 before exiting useLocallocal static x is 50 on entering useStaticLocallocal static x is 51 on exiting useStaticLocalglobal x is 1 on entering useGlobalglobal x is 10 on exiting useGloballocal x in useLocal is 25 after entering useLocallocal x in useLocal is 26 before exiting useLocallocal static x is 51 on entering useStaticLocallocal static x is 52 on exiting useStaticLocalglobal x is 10 on entering useGlobalglobal x is 100 on exiting useGloballocal x in main is 5

  • 8/12/2019 introduction to computing lec 5

    54/68

    Recursion

    Recursive functions Functions that call themselves

    Can only solve a base case

    Divide a problem up into

    What it can do

    What it cannot do

    What it cannot do resembles original problem

    The function launches a new copy of itself (recursion step) to

    solve what it cannot do Eventually base case gets solved

    Gets plugged in, works its way up and solves whole problem

  • 8/12/2019 introduction to computing lec 5

    55/68

    Recursion

    Example: factorials 5! = 5 * 4 * 3 * 2 * 1

    Notice that

    5! = 5 * 4! 4! = 4 * 3! ...

    Can compute factorials recursively

    Solve base case (1! = 0! = 1) then plug in

    2! = 2 * 1! = 2 * 1 = 2; 3! = 3 * 2! = 3 * 2 = 6;

  • 8/12/2019 introduction to computing lec 5

    56/68

    Recursive evaluation of 5!.

    1 /* Fig. 5.14: fig05_14.c2

  • 8/12/2019 introduction to computing lec 5

    57/68

    57

    2 Recursive factorial function */3 #include4

    5 longfactorial( longnumber ); /* function prototype */6

    7 /* function main begins program execution */8 intmain( void)9 {10 inti; /* counter */1112 /* loop 11 times; during each iteration, calculate13 factorial( i ) and display result */14 for( i = 0; i

  • 8/12/2019 introduction to computing lec 5

    58/68

    58

    23 longfactorial( longnumber )24 {25 /* base case */26 if( number

  • 8/12/2019 introduction to computing lec 5

    59/68

    Example Using Recursion: Fibonacci Series

    Fibonacci series: 0, 1, 1, 2, 3, 5, 8... Each number is the sum of the previous two Can be solved recursively:

    fib( n ) = fib( n - 1 ) + fib( n 2 )

    Code for thefibonacci

    functionlong fibonacci( long n )

    {

    if (n == 0 || n == 1) // base case

    return n;

    else

    return fibonacci( n - 1) +fibonacci( n 2 );

    }

    1 /* Fig. 5.15: fig05_15.c2 Recursive fibonacci function */

  • 8/12/2019 introduction to computing lec 5

    60/68

    60

    3 #include4

    5 longfibonacci( longn ); /* function prototype */6

    7 /* function main begins program execution */8 intmain( void)9 {10 longresult; /* fibonacci value */11 longnumber; /* number input by user */12

    13 /* obtain integer from user */14 printf( Enter an integer: );15 scanf( %ld , &number );16

    17 /* calculate fibonacci value for number input by user */18 result = fibonacci( number );19

    20 /* display result */21 printf( Fibonacci( %ld ) = %ld\n , number, result );22

    23 return0; /* indicates successful termination */24

    25 } /* end main */26

    27 /* Recursive definition of function fibonacci */28 longfibonacci( longn )

  • 8/12/2019 introduction to computing lec 5

    61/68

    61

    29 {30 /* base case */31 if( n == 0|| n == 1) {32 returnn;33 } /* end if */34 else{ /* recursive step */35 returnfibonacci( n - 1) + fibonacci( n - 2);36 } /* end else */37

    38 } /* end function fibonacci */

    Enter an integer: 0Fibonacci( 0 ) = 0

    Enter an integer: 1Fibonacci( 1 ) = 1

    Enter an integer: 2Fibonacci( 2 ) = 1(continued on next sl ide )

    (continued from previous sl ide)

  • 8/12/2019 introduction to computing lec 5

    62/68

    Enter an integer: 3Fibonacci( 3 ) = 2

    Enter an integer: 4Fibonacci( 4 ) = 3

    Enter an integer: 5Fibonacci( 5 ) = 5

    Enter an integer: 6Fibonacci( 6 ) = 8(continued on next sl ide )

    (continued from previous sl ide)

  • 8/12/2019 introduction to computing lec 5

    63/68

    Enter an integer: 10Fibonacci( 10 ) = 55

    Enter an integer: 20Fibonacci( 20 ) = 6765

    Enter an integer: 30Fibonacci( 30 ) = 832040

    Enter an integer: 35Fibonacci( 35 ) = 9227465

  • 8/12/2019 introduction to computing lec 5

    64/68

    Set of recursive calls for fibonacci 3).

  • 8/12/2019 introduction to computing lec 5

    65/68

    Array Sum

  • 8/12/2019 introduction to computing lec 5

    66/68

    Array Sum

  • 8/12/2019 introduction to computing lec 5

    67/68

    Recursion vs. Iteration

    Repetition Iteration: explicit loop

    Recursion: repeated function calls

    Termination Iteration: loop condition fails

    Recursion: base case recognized

    Both can have infinite loops

  • 8/12/2019 introduction to computing lec 5

    68/68

    Recursion examples and exercises

    Examples o Recursion: Factorial function

    Fibonacci functionGreatest common divisor

    Sum of two integers

    Multiply two integers

    Raising an integer to an integer power

    Printing keyboard inputs in reverse

    Example of Recursion

    After we cover Arraya

    Sum the elements of an array

    Print an array

    Print an array backwardPrint a string backward

    Check if a string is a palindrome

    Minimum value in an array

    Selection sort

    Quicksort

    Linear search

    Binary search

    Recursion examples and exercises in the course.