+ All Categories
Home > Documents > Shivani Varshney/RCET/Programming With C

Shivani Varshney/RCET/Programming With C

Date post: 30-May-2018
Category:
Upload: sonu1070
View: 220 times
Download: 0 times
Share this document with a friend

of 62

Transcript
  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    1/62

    Functions

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    2/62

    Introduction

    Divide and conquer Construct a program from smaller pieces or components

    These smaller pieces are called modules Each piece more manageable than the original program

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    3/62

    Program Modules in C

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

    functionsC 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 taskWorker gets information, does task, returns result Information hiding: boss does not know details

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    4/62

    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 ) );

    Calls function sqrt, which returns the square root of its argumentAll math functions return data type double

    Arguments may be constants, variables, or expressions

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    5/62

    Functions

    Functions Modularize a program All variables declared inside functions are local variables

    Known only in function defined ParametersCommunicate information between functionsLocal variables

    Benefits of functions Divide and conquerManageable program development

    Software reusabilityUse existing functions as building blocks for new programsAbstraction - hide internal details (library functions)

    Avoid code repetition

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    6/62

    Function Definitions

    Function definition formatreturn-value-type function-name( parameter-list ){

    declarations and statements

    } Function-name: any valid identifier

    Return-value-type: data type of the result (default int)void indicates that the function returns nothing

    Parameter-list: comma separated list, declares parametersA type must be listed explicitly for each parameter unless, the

    parameter is of type int

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    7/62

    Function Definitions

    Function definition format (continued)return-value-type function-name( parameter-list ){

    declarations and statements}

    Declarations and statements: function body (block) Variables can be declared inside blocks (can be nested)Functions can not be defined inside other functions

    Returning control If nothing returned return; or, until reaches right brace

    If something returned returnexpression;

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    8/62

    1. Functionprototype (3parameters)

    2. Input values

    2.1 Call function

    3. Functiondefinition

    Program Output

    1 /* Fig. 5.4: fig05_04.c2 Finding the maximum of three integers */3 #include 45 int maximum( int, int, int ); /* function prototype */67 int main()

    8 {9 int a, b, c;1011 printf( "Enter three integers: " );12 scanf( "%d%d%d", &a, &b, &c );13 printf( "Maximum is: %d\n", maximum( a, b, c ) );1415 return 0;

    16 }1718 /* Function maximum definition */19 int maximum( int x, int y, int z )20 {21 int max = x;2223 if ( y > max )

    24 max = y;2526 if ( z > max )27 max = z;2829 return max;30 }

    Enter three integers: 22 85 17Maximum is: 85

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    9/62

    Function Prototypes

    Function prototype Function name Parameters what the function takes in Return type data type function returns (default int)

    Used to validate functions Prototype only needed if function definition comes after use in

    program The function with the prototype

    int maximum( int, int, int );

    Takes in 3 intsReturns an int

    Promotion rules and conversions Converting to lower types can lead to errors

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    10/62

    Header Files

    Header files Contain function prototypes for library functions

    ,, etc Load with

    #include #include

    Custom header files Create file with functions

    Save as filename.h Load in other files with #include "filename.h"

    Reuse functions

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    11/62

    Calling Functions: Call by Value and Call byReference

    Used when invoking functionsCall by value Copy of argument passed to function Changes in function do not effect original Use when function does not need to modify argumentAvoids 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

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    12/62

    Random Number Generation

    randfunction Load Returns "random" number between 0 and RAND_MAX (at least32767)

    i = rand();

    Pseudorandom Preset sequence of "random" numbers Same sequence for every function call

    Scaling To get a random number between 1 and n

    1 + ( rand() % n ) rand() % n returns a number between 0 and n - 1Add 1 to make random number between 1 and n1 + ( rand() % 6) number between 1 and 6

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    13/62

    Random Number Generation

    srandfunction

    Takes an integer seed and jumps to that location in its"random" sequence

    srand( seed);

    srand( time( NULL ) ); //load time( NULL ) Returns the time at which the program was compiled in seconds

    Randomizes" the seed

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    14/62

    1. Initialize seed

    2. Input value forseed

    2.1 Use srandtochange randomsequence

    2.2 Define Loop

    3. Generate andoutput randomnumbers

    1 /* Fig. 5.9: fig05_09.c

    2 Randomizing die-rolling program */

    3 #include

    4 #include

    5

    6 int main()7 {

    8 int i;

    9 unsignedseed;

    10

    11 printf( "Enter seed: " );

    12 scanf( "%u", &seed );

    13 srand( seed );

    14

    15 for ( i = 1; i

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    15/62

    Program OutputEnter seed: 867

    2 4 6 1 6

    1 1 3 6 2

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

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

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    16/62

    Storage Classes

    Storage class specifiers Storage duration how long an object exists in memory Scope where object can be referenced in program Linkage specifies the files in which an identifier is known

    (more in Chapter 14)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 registersCan only be used for automatic variables

    register int counter = 1;

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    17/62

    Storage Classes

    Static storage Variables exist for entire program execution

    Default value of zero

    static: local variables defined in functions.Keep value after function ends

    Only known in their own function

    extern: default for global variables and functionsKnown in any function

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    18/62

    Scope Rules

    File scope Identifier defined outside function, known in all functions

    Used for global variables, function definitions, functionprototypes

    Function scope Can only be referenced inside a function body

    Used only for labels (start:, case: , etc.)

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    19/62

    Scope Rules

    Block scope Identifier declared inside a blockBlock scope begins at declaration, ends at right brace

    Used for variables, function parameters (local variables of

    function) Outer blocks "hidden" from inner blocks if there is a variable

    with the same name in the inner block

    Function prototype scope Used for identifiers in parameter list

    Shivani Varshney/RCET/Programming with C

    1 /* Fig 5 12: fig05 12 c

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    20/62

    1. Functionprototypes

    1.1 Initializeglobal variable

    1.2 Initialize localvariable

    1.3 Initialize localvariable in block

    2. Call functions

    3. Output results

    1 /* Fig. 5.12: fig05_12.c2 A scoping example */3 #include 45 voida(void); /* function prototype */6 voidb(void); /* function prototype */7 voidc(void); /* function prototype */89 int x = 1; /* global variable */1011 int main()12 {13 int x = 5; /* local variable to main */14

    15 printf("local x in outer scope of main is %d\n", x );1617 { /* start new scope */18 int x = 7;1920 printf( "local x in inner scope of main is %d\n",x );21 } /* end new scope */

    2223 printf( "local x in outer scope of main is %d\n", x );2425 a(); /* a has automatic local x */26 b(); /* b has static local x */27 c(); /* c uses global x */28 a(); /* a reinitializes automatic local x */

    29 b(); /* static local x retains its previousvalue */30 c(); /* global x also retains its value */

    31

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    21/62

    3.1 Functiondefinitions

    31

    32 printf( "local x in main is %d\n", x );

    33 return 0;

    34 }

    35

    36voida(void)

    37 {38 int x = 25; /* initialized each time a is called */

    39

    40 printf( "\nlocal x in a is %d after entering a\n", x );

    41 ++x;

    42 printf( "local x in a is %d before exiting a\n", x );

    43 }

    4445voidb(void)

    46 {

    47 staticint x = 50; /* static initialization only */

    48 /* first time b is called */

    49 printf( "\nlocal static x is %d on entering b\n", x );

    50 ++x;

    51 printf( "local static x is %d on exiting b\n", x );

    52 }

    53

    54voidc(void)

    55 {

    56 printf( "\nglobal x is %d on entering c\n", x );

    57 x *= 10;

    58 printf( "global x is %d on exiting c\n", x );

    59 }

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    22/62

    Program Output

    local x in outer scope of main is 5local x in inner scope of main is 7local x in outer scope of main is 5local x in a is 25 after entering alocal x in a is 26 before exiting alocal static x is 50 on entering blocal static x is 51 on exiting bglobal x is 1 on entering cglobal x is 10 on exiting c

    local x in a is 25 after entering alocal x in a is 26 before exiting alocal static x is 51 on entering blocal static x is 52 on exiting bglobal x is 10 on entering cglobal x is 100 on exiting clocal x in main is 5

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    23/62

    Pointers as function arguments

    We can pass the address of a variable as an argument to afunction.

    When we pass addresses to a function, the parametersreceiving the addresses should be pointers.

    The process of calling a function using pointers to passthe addresses of variables is known as call by reference.

    The function which is called by reference can change thevalue of the variableused in the call.

    This mechanism is also known as call by address or passby pointers.

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    24/62

    1. The function parameters are declared as pointers.

    2. The dereferencing pointers are used in thefunction body.

    3. When the function is called, the addresses arepassed as actual arguments.

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    25/62

    Passing array to function

    One dimensional arrays : To pass a one-dimensional array to a called function, it is sufficient to list

    the name of the array, without any subscripts and the size of the array asarguments.

    For example :

    Declaration : void largest(int [ ],int); Calling : largest(a,n)

    Definition : void largest(int a[ ],int n)

    {

    }

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    26/62

    Three rules to pass an array to a function

    The function must be called by passing only the name of the array.

    for example : largest(a);

    In the function definition, the formal parameter must be an arraytype, the size of the array does not need to be specified.

    for example : void largest(int a[ ]){

    } The function prototype must show that the argument is an array.

    for example : void largest(int [ ]);

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    27/62

    Two Dimensional Array

    The rules are :

    The function must be called by passing only the array name.

    for example : average(matrix,m,n);

    In the function definition, we must indicate that the array has two

    dimensions by including two sets of brackets.for example : void average(int matrix[ ][n],int m,int n)

    {

    }

    The size of the second dimension must be specified.

    The prototype declaration should be similar to function header.

    for example : void average(int matrix[ ][n],int,int);

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    28/62

    Passing strings to functions

    The string to be passed must be declared as a formal argument ofthe function when it is defined.

    for example : void display(char str[ ])

    {

    }

    The function prototype must show that the argument is a string

    void display(char str[ ]);

    A call to the function must have a string array name withoutsubscripts as its actual argument.

    display(str);

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    29/62

    Using Library Functions

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    30/62

    Standard Library Function Prototypes

    Any standard library function used by your program mustbe prototyped.

    Appropriate header for each library function has to beused.

    All necessary headers are provided by the C compiler.

    The library headers are (usually) files that use the .hextension.

    A header contains two main elements: any definitions used by the library functions and the prototypes for the libraryfunctions.

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    31/62

    For example, is included in almost all programsbecause it contains the prototype for printf( ).

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    32/62

    Macro Definitions

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    33/62

    The #define directive has another powerful feature:The macro name can have arguments. Each time themacro name is encountered, the arguments used inits definition are replaced by the actual argumentsfound in the program. This form of a macro is calledafunction-like macro.

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    34/62

    Example

    #include

    #define ABS(a) (a) < 0 ? -(a) : (a)

    int main(void)

    {

    printf("abs of -1 and 1: %d %d", ABS(-1), ABS

    (1));

    return 0;

    }

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    35/62

    When this program is compiled, a in the macrodefinition will be substituted with the values 1 and1. The parentheses that enclose a ensure propersubstitution in all cases.

    ABS (10-20) would be converted to

    10-20 < 0 ? -10-20 : 10-20

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    36/62

    Preprocessor Directive

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    37/62

    Preprocessor directives are lines included in the codeof our programs that are not program statements butdirectives for the preprocessor.

    These lines are always preceded by a hash sign (#). The preprocessor is executed before the actual

    compilation of code begins, therefore thepreprocessor digests all these directives before any

    code is generated by the statements.

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    38/62

    The preprocessor directives are shown here:

    #define #endif #ifdef #line

    #elif #error #ifndef #pragma#else #if #include #undef

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    39/62

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    40/62

    There is no semicolon in this statement. There may beany number of spaces between the identifier and thecharacter sequence, but once the character sequence

    begins, it is terminated only by a newline.

    Example: If we wish to use the word LEFT for the value 1 and the word

    RIGHT for the value 0, we could declare these two #definedirectives:

    #define LEFT 1#define RIGHT 0

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    41/62

    This causes the compiler to substitute a 1 or a 0 eachtime LEFT or RIGHT is encountered in your

    source file.

    For example, the following prints 0 1 2 on the screen:printf("%d %d %d", RIGHT, LEFT, LEFT+1);

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    42/62

    #error

    The #error directive forces the compiler to stopcompilation. It is used primarily for debugging. Thegeneral form of the #error directive is

    #error error-messageThe error-message is not between double quotes.

    When the #error directive is encountered, the

    error message is displayed, possibly along with other

    information defined by the compiler.

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    43/62

    #include

    The #include directive tells the compiler to readanother source file in addition to the one thatcontains the #include directive.

    The name of the source file must be enclosedbetween double quotes or angle brackets.

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    44/62

    Example,

    #include "stdio.h"

    #include

    Both cause the compiler to read and compile theheader for the I/O system library functions.

    Include files can have #include directives in them. Thisis referred to as nested includes.

    The number of levels of nesting allowed varies betweencompilers.

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    45/62

    Conditional Compilation Directives

    There are several directives that allows to selectivelycompile portions of your program's source code. Thisprocess is called conditional compilation and is usedwidely by commercial software houses that provideand maintain many customized versions of oneprogram.

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    46/62

    #if, #else, #elif, and #endif

    These directives allow you to conditionally includeportions of code based upon the outcome of aconstant expression.

    The general form of#if is#ifconstant-expression

    statement sequence

    #endif

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    47/62

    If the constant expression following #if is true, the code that isbetween it and #endif is compiled.

    Otherwise, the intervening code is skipped. The #endifdirective marks the end of an #if block.

    For example:/* Simple #if example. */

    #include

    #define MAX 100

    int main(void)

    This program displays the message on the screen becauseMAX is greater than 99.

    {

    #if MAX>99

    printf(''Compiled for array

    greater than 99.\n");

    #endifreturn 0;

    }

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    48/62

    The #else directive works much like the else that ispart of the C language:

    It establishes an alternative if #if fails. The previous

    example can be expanded as shown here:

    /* Simple #if/#else example. */

    #include

    #define MAX 10

    int main(void)

    {

    #if MAX>99printf("Compiled for array greaterthan 99.\n");#else

    printf("Compiled for smallarray.\n");#endifreturn 0;}

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    49/62

    Some pointer concepts

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    50/62

    Pointer I

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    51/62

    Pointer II

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    52/62

    Pointer III

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    53/62

    Pointer IV

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    54/62

    Pointer V

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    55/62

    Pointer VI

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    56/62

    Recursion

    Recursive functions Functions that call themselves

    Can only solve a base case

    Divide a problem up into

    What it can doWhat 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 solvedGets plugged in, works its way up and solves whole problem

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    57/62

    Recursion

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

    Notice that5! = 5 * 4!

    4! = 4 * 3! ... Can compute factorials recursively

    Solve base case (1! = 0! = 1) then plug in2! = 2 * 1! = 2 * 1 = 2;

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

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    58/62

    Example Using Recursion: The 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 the fibaonacci functionlong fibonacci( long n )

    {

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

    return n;

    elsereturn fibonacci( n - 1) +

    fibonacci( n 2 );

    }

    Shivani Varshney/RCET/Programming with C

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    59/62

    1 /* Fig. 5.15: fig05_15.c

    2 Recursive fibonacci function */

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    60/62

    1. Functionprototype

    1.1 Initializevariables

    2. Input an integer

    2.1 Call functionfibonacci

    2.2 Output results.

    3. Define

    fibonaccirecursively

    Program Output

    3 #include 45 long fibonacci( long );67 int main()

    8 {9 long result, number;1011 printf( "Enter an integer: " );12 scanf( "%ld", &number );13 result = fibonacci( number );14 printf( "Fibonacci( %ld ) = %ld\n", number, result );

    15 return 0;16 }1718 /* Recursive definition of function fibonacci */19 long fibonacci( long n )20 {21 if ( n == 0 || n == 1 )

    22 return n;23 else24 return fibonacci( n - 1 ) + fibonacci( n - 2 );25 }Enter an integer: 0Fibonacci(0) = 0Enter an integer: 1

    Fibonacci(1) = 1

    Enter an integer: 2Fibonacci(2) = 1

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    61/62

    Program Output

    Enter an integer: 3Fibonacci(3) = 2Enter an integer: 4

    Fibonacci(4) = 3Enter an integer: 5Fibonacci(5) = 5Enter an integer: 6Fibonacci(6) = 8

    Enter an integer: 10Fibonacci(10) = 55Enter an integer: 20Fibonacci(20) = 6765Enter an integer: 30

    Fibonacci(30) = 832040Enter an integer: 35Fibonacci(35) = 9227465

  • 8/14/2019 Shivani Varshney/RCET/Programming With C

    62/62

    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

    Balance Choice between performance (iteration) and good software

    engineering (recursion)


Recommended