user defined udf

Upload: chetankhs

Post on 07-Apr-2018

278 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 User Defined Udf

    1/27

    CS110/101 Algorithmic Approach to ProblemSolving

    USER-DEFINED FUNCTIONS

    INTRODUCTION

    One of the strength of C functions are easy to define and use. C functions can be

    classified into two categories, namely, Library( Not required to be written by us ) and

    User-Defined(developed by the user at the time of writing a program) functions. main is

    an example of user-defined functions. printfand scanfbelong to the category of library

    functions. However, a user-defined function can later become a part of the C program

    library.In fact, this is one of the strength of C language.

    Need for User-DefinedFunctions:

    main is a specially recognized function in C. Every program must have a main function

    to indicate where the program has to begin its execution. While it is possible to code any

    program utilizing only main function, it leads to a number of problems. The program

    may become too large and complex and as a result the task of debugging, testing and

    maintaining becomes difficult. If a program is divided into functional parts, then each

    part may be independently coded and later combined into a single unit. These

    subprograms called FUNCTIONSare much easier to understand, debug and test.

    There are times when certain type of operations or calculations is repeated at many points

    throughout a program. We may repeat the program statements whenever they are

    needed. It is another approach to design a program that can be called and used whenever

    required. This saves both time and space.

    The various advantages of functions are:The various advantages of functions are:

    Reusability and Reduction of code size: The existing functions can be re-used asbuilding blocks to create new programs which results in reduced program size. The

    functions can be used any number of times.

    Readability of the program can be increased: One can keep track of what each functionis doing.

    Modular Programming approach: Large program is divided into small sub programs,each performs individual/specific task which makes the program development moremanageable.

    Easier to Debug: Locating and isolating the errors are becomes much easier.

    Built Library: Repeatedly used functions can be generalized, tested and kept in a library

    for future use. It reduces program development time and coding time.

    Functions Sharing: Functions can be shared by many programs / Programmers.

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 1 of 27

  • 8/3/2019 User Defined Udf

    2/27

    CS110/101 Algorithmic Approach to ProblemSolving

    The division approach clearly results in a number of advantages.

    1. It facilitates top-down modular programming style. In this, the high-level logic of

    the overall problem is solved first. While the details of each lower-level functionsare addressed later.

    2. The length of a source program can be reduced by using functions at appropriate

    places.

    3. It is easy to locate and isolate a faulty function for further investigations.

    4. A function may be used by many other programs. This means that a C

    programmer can build on what have others have already done, instead of starting

    allover again from scratch.

    Figure: Top-down modular programming using functions

    A Multi-Functions Program:A function is a self-contained block of code that performs a particular task. Once a

    function has been designed and packed, it can be treated as a black boxthat takes some

    data from the main program and returns a value. Every C program can be designed by

    using a collection of these black-boxes known as functions.

    Illustration of the use of C functions

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 2 of 27

    MAIN PROGRAM

    FunctionA

    FunctionB

    FunctionC

    B1 B2

    void printline (void); /* Declaration */

    main()

    {

    printline();

    printf(This illustrates the use of C functions);

    printline();

    }

    void printline(void)

    {int i;for(i=1 ; i < 40 ; i++ )

    printf(-);printf(\n);

    }

  • 8/3/2019 User Defined Udf

    3/27

    CS110/101 Algorithmic Approach to ProblemSolving

    The main functions calls the user-defined printline function two times and the library

    function printf once. We may notice that the printline function itself calls the library

    functionprintf39 times repeatedly. Any function can call any other function. In fact, itcan call itself. A called function can also call another function. A function can be

    called more than once. In fact, this is one the main features of using functions.

    Except the starting point, there are no other pre-determined relationships, rules ofprecedence or hierarchies among the functions that make up a complete program. Thefunctions can be placed in any order. A called function can be placed either before or

    after the calling function. However it is the usual practice to put all the called functions

    at the end (Modular programming).

    Figure:Flow control in a multi-function program.

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 3 of 27

    mian ()

    {. . . . .

    . . . . .

    . . . . .

    function1();. . . . .

    . . . . .

    function2();

    . . . . .

    . . . . .

    function1();

    . . . . .

    }

    function1 (){

    . . . . .

    . . . . .

    . . . . .}

    function2 ()

    {

    . . . . .function3 ();

    . . . . .

    }

    function3 (){

    . . . . .

    . . . . .

    . . . . .

    }

  • 8/3/2019 User Defined Udf

    4/27

    CS110/101 Algorithmic Approach to ProblemSolving

    Modular ProgrammingModular Programming

    Modular Programming is a strategy applied to the design and development of Software

    systems. It is defined as organizing a large program into small, independent programs

    segments called modules that are separately named and individually callable program

    units. These modules are carefully integrated to become a software system that satisfies

    the system requirements. It is basically a Divide-and-Conquer approach to problem

    solving. In C, each module refers to a function that is responsible for a single task.

    Characteristics of modular programming:

    Each moduleshould do only one thing.

    Communication between modules is allowed only by a calling module.

    A module can be called by one and only one higher module.

    No communication can take place directly between modules that do not havecalling-called relationship.

    All modules are designed as single-entry, single-exit systems using control

    structures.

    Elements ofUser-DefinedFunctions:

    Functions are classified as one of the derived data types in C, therefore define functions

    and use them like any other variables in C programs.Similarities between functions and variables in C:

    Both function names and variable names are considered identifiers and mustfollow the rules same as identifiers.

    Like variables, functions have types associated with them. ( such as int, float, )

    Like variables, functions names and their types must be declared and definedbefore they are used in a program.

    In order to make use of a user-defined function, we need to establish three elements that

    are related to functions.

    1. Function Definition: An independent program module, specially written to

    implement the requirements of the function.

    2. Function Call: Used to invoke function at a required place in the program.

    3. Function Declaration / Prototype: Like declaration of a variable, function should

    be declared to use later in the program.

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 4 of 27

  • 8/3/2019 User Defined Udf

    5/27

    CS110/101 Algorithmic Approach to ProblemSolving

    Definitions of Functions:

    It is also known as Function Implementation, include the following elements,

    Function Name

    Function Type Function Header

    List of Parameters

    Local Variable Declarations

    Function Statements Function Body

    A return Statement

    All the six elements are mainly grouped into two parts, namely,

    Function Header ( The First Three Elements ) &

    Function Body ( The Second Three Elements )

    The general format of a function definition to implement above two parts is given below:

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 5 of 27

    function_type function_name( parameter list )

    {

    local variable declaration ;

    executable statement1 ;

    executable statement2 ;

    . . . . .

    . . . . .

    return statement ;

    }

    #include

    void add();

    void main(){

    add();

    }

    void add()

    {

    int a = 10, b = 15, sum ;

    sum = a + b ;printf(\n Sum of 10 + 15 = %d, sum);

    }

    Function

    Definition

    Function

    Call

    Function

    DeclarationFunctionE

    lements

  • 8/3/2019 User Defined Udf

    6/27

    CS110/101 Algorithmic Approach to ProblemSolving

    The first line f u n c t io n _ t y pe f u n c t io n _ n a me ( p a r a m et e r l i s t ) is

    known as the Function Headerand the statements within the opening and closing braces

    constitute thefunction body, which is compound statement.

    FUNCTION HEADER: It has three parts, The Function Type / Return Type

    The Function Name and

    The Formal Parameter

    The Function Type / Return Type:

    It specifies the type of value ( like int, float or double ) that the function is expected to

    return to the program calling the function.

    If the return type is not explicitly specified, C will assume that it is an integer type by

    (default) i.e., default return type is integer for unspecified function type.

    If the function is not returning anything, then we need to specify the return type as

    void.

    It is a good practice to code explicitly the return type, even when it is an integer. TheIt is a good practice to code explicitly the return type, even when it is an integer. The

    value returned is the output produced by the function.value returned is the output produced by the function.

    The Function Name:

    It is any valid C identifier or variable names, the name should be appropriate to the task

    performed by the function. Avoid duplicating library routine names or operating system

    commands.

    The Formal Parameter List

    It declares the variables that will receive the data sent by the calling program/function. It

    serves as input data to the function to carry out the specified task. They represent actual

    input values. The parameters are also known as arguments.

    The parameter list contains declaration of variables separated by commas and

    surrounded by parentheses.Examples:

    float quadratic ( int a, int b, int c) {..}double power ( double x, int n ) {..}

    float mul ( float x, float y) {..}

    int sum ( int a, int b ) {..}

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 6 of 27

  • 8/3/2019 User Defined Udf

    7/27

    CS110/101 Algorithmic Approach to ProblemSolving

    Remember, there is no semicolon after the closing parenthesis and the declaration of

    parameter variables cannot be combined. Example: int sum ( int a, b ) is illegal.

    A function need not always receive values from the calling program, in such cases,

    functions have no formal parameters, and then we use voidbetween the parentheses as in

    void printline (void) or void printline ( )

    {

    . . . . .

    . . . . .

    }

    This function neither receives any input values nor returns back nay value. It is a good

    programming style to use void to indicate a null parameter list.

    FUNCTION BODY: It has three parts,

    This contains the declaration and statements necessary for performing the required task,

    enclosed in braces, contains three parts, in the below order:

    1. Local Declarations that specify the variables needed by the function.

    2. Function Statements that perform the task of the function.

    3. AReturn Statementthat returns the value evaluated by the function.

    If a function does not return any value, we can omit the return statement. However, note

    that its return type should be specified as void. Again, it is nice to have a return statement

    even forvoid function.

    NOTENOTE

    When a function reaches its return statement, the control is transferred back to theWhen a function reaches its return statement, the control is transferred back to the

    calling program. In the absence of a return statement, the closing brace acts as acalling program. In the absence of a return statement, the closing brace acts as a

    void returnvoid return..

    AA local Variablelocal Variable is a variable that is defined inside a function and used withoutis a variable that is defined inside a function and used without

    having any role in the communication between functions.having any role in the communication between functions.

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 7 of 27

  • 8/3/2019 User Defined Udf

    8/27

    CS110/101 Algorithmic Approach to ProblemSolving

    Return Values and Their Types:

    A function may or may not send back any value to the calling function. If it does, it is

    done through the return statement. It is possible to pass to the called function any

    number of values; the called function can only return one value per call, at the most.

    The return statement can take one of the following forms

    return; /* plain return does not return any value, the control is immediately

    passed back to the calling function when a return is encountered. */

    Example: if(error)

    return;

    return(expression); /* returns the value of the expression */

    Example: int add(int a, int b)

    {return(a+b);

    }

    All functions by default return int type data. One can force a function to return a

    particular type of data by using a type specifier in the function header. When a value is

    returned, it is automatically cast to the functions type. For instance, the function

    int product (void)

    {

    return ( 2.5 * 3.0 ) ;

    }

    will return the value 7, only the integer part of the result. The return value will be

    truncated to an integer.

    Function Calls:

    A function can be called by simply using the function name followed by a list of actual

    parameters or arguments, if any enclosed in parentheses.

    Example: main(){

    int y;

    y = mul(10,5); /* Function Call */ printf(%d\n,y);

    }

    When the compiler encounters a function call, the control is transferred to the function

    mul(). This function is then executed line by line as described and a value is returned

    when a return statement is encountered. This value is assigned to y.

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 8 of 27

  • 8/3/2019 User Defined Udf

    9/27

    CS110/101 Algorithmic Approach to ProblemSolving

    The function call sends two integer values 10 & 5 to the function.

    int mul(int x, int y) which are to x = 10 and y = 5 respectively. The function computes

    the product x and y , assigns the result to the local variable p, and then returns value 25 tothe main where it is assigned to y .

    There are different ways to call a function. mul() function can be invoked:

    mul(10,5)

    mul(m,5)

    mul(10,n)

    mul(m,n)

    mul(m+5,10)

    mul(10,mul(m,n)) /* uses its own call as its one of the parameter */

    mul(expresssion1 ,expression2) /*expression should be evaluated to single

    values that can be passed as actualparameters. */

    A function which returns a value can be used in expression like any other variable.

    Example:

    printf(%d\n, mul(p,q));

    y = mul(p,q) / ( p+q) ;

    if (mul(m,n) > total )

    printf(%d, max );

    A function cannot be used as mul(a,b) = 15 ; is invalid.

    A function that does not return any value may not be used in expressions, but can be

    called in to perform certain tasks specified in the function.Example: main()

    {

    printline(); /* Note that the presence of a semicolon at the end */

    }

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 9 of 27

    main()

    {

    int y;

    y = mul(10,5) ; /* call */

    }

    int mul ( int x, int y )

    {

    int p; /* local variable */

    p = x * y ; /* x = 10 , y = 5 */

    return (p);

    }

  • 8/3/2019 User Defined Udf

    10/27

    CS110/101 Algorithmic Approach to ProblemSolving

    Function CallFunction Call

    A function call is a postfix expression. When a function call is used as a part of an

    expression, it will be evaluated first, unless parentheses are used to change the order ofprecedence. In a function call, thefunction name is the operandand the parentheses set

    (..) which contains the actual parameters is the operand. The actual parameters mustmatch the functions formal parameters in type, order and number. Multiple actual

    parameters must be separated by commas.

    Note:Note:

    1. If the actual parameters are more than the formal parameters, the extra actual

    arguments will be discarded.2. If actual parameters are less than the formal parameters, the unmatched formal

    arguments will be initialized to some garbage.

    3. Any mismatch I data types may also result in some garbage values.

    Function Declaration: also known as Function Prototype

    Like variables, all functions in a C program must be declared, before they are invoked. A

    function declaration consists of four parts.

    Function Type ( Return Type )

    Function Name

    Function Parameter List

    Terminating Semicolon, in the following format:

    It is similar to the function header line except the terminating semicolon.

    Example : int mul ( int x, int y ) ; /* Function Prototype */

    Important Note:Important Note:

    1. The parameter list must be separated by commas.2. The parameter names do not need to be the same in the prototype declaration and

    the function definition.

    3. Use of parameter names in the declaration is optional.

    4. If the function has no formal parameters, the list is written as (void).Example: void print_line(void) { . . .}

    5. The return type is optional, when the function returns inttype data.

    6. The return type must be void if no value is retuned.7. When the declared types do not match with the types in the function definition,

    compiler will produce an error.

    Example: (Valid/Acceptable) mul ( int, int);

    mul ( int x, int y);

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 10 of 27

    function-type function-name ( parameter list );

  • 8/3/2019 User Defined Udf

    11/27

    CS110/101 Algorithmic Approach to ProblemSolving

    int mul ( int, int);

    When a function does not take any parameters and does not return any value, its

    prototype is written as: void function_name (void) ;

    A prototype declaration may be placed in two places:

    1. Above all the functions ( includingmain() ) ; /* In the global declaration section,

    referred as a global prototype , available for all function in the program. */

    2. Inside a function definition ; /* in the local declaration section, referred as a local

    prototype , are used by the functions containing them */

    The place of declaration of a function defines a region in a program in which the

    function may be function may be used by other functions. This region is known as the

    scope of the function. It is good programming style to declare prototypes in the global

    declaration section before main(). It adds flexibility, provides an excellent quick

    reference to the functions used in the program, and enhances documentation(readability).

    Proto Types: Yes / NoProto Types: Yes / No

    Prototype declarations are not essential. If a function has not been declared before it isused, C will assume that its details available at the time of linking. If these assumptions

    are wrong, the linker will fail. The moral is that we must always include prototypedeclarations, preferably in global declaration section.

    ParametersParameters also known asalso known asArgumentsArguments

    Are used I three places;. In Declaration ( Prototype ) : are calledFormal Parameters

    2. In Function Call :are calledActual Parameters. In Function Definition : are calledFormal Parameters

    Actual Parameters used in a calling statement may be simple constants, variables or

    expressions. Theformaland actualparameters must match exactly in type, order, and

    number. Their names do not need to match.

    Category of Functions:

    A function, depending on whether arguments are present or not and whether a value is

    returned or not, may belong to one of the following categories:

    Category-1: Functions with no arguments and no return values.

    Category-2: Functions with arguments and no return values.

    Category-3: Functions with arguments and one return value.

    Category-4: Functions with no arguments and but return a value.

    Category-5: Functions that return multiple values.

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 11 of 27

  • 8/3/2019 User Defined Udf

    12/27

    CS110/101 Algorithmic Approach to ProblemSolving

    No Arguments and No Return Values:

    When a function has no arguments, it does not receive any data from the calling function.

    Similarly, when it does not return a value, the calling function does not receive any data

    from the called function. In effect, there is no data transfer between the calling function

    and the called function. This indicates that there is only a transfer of control but no

    data.

    Calling Function Called Function

    Figure: No data communication between functions

    Note: A function does not return any value cannot be used in the expression. It can only

    be used as an independent statement. When there is nothing to be returned, the return

    statement is optional. The closing brace of the function signals the end of execution of thefunction, thus returning the control, back to the calling function.

    Arguments but No Return Values:

    The calling function has no control over the way the functions receives input data. We

    could make the calling function to read data from the terminal and pass it on to the called

    function. The calling function can check for the validity of data, if necessary, before it is

    handed over to the called function.

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 12 of 27

    Control / No Input

    Control / No Output

    fucntion-1( )

    {

    . . . . .

    . . . . .function-2( );

    . . . . .

    . . . . .}

    fucntion-2( )

    {

    . . . . .

    . . . . .

    . . . . .

    . . . . .

    . . . . .}

    Control / Values of Arguments

    Control /No Return Value

    fucntion-1( )

    {. . . . .. . . . .

    function-2(a);

    . . . . .

    . . . . .

    }

    fucntion-2(x)

    {. . . . .. . . . .

    . . . . .

    . . . . .

    . . . . .

    }

  • 8/3/2019 User Defined Udf

    13/27

    CS110/101 Algorithmic Approach to ProblemSolving

    Calling Function Called Function

    Figure: One-way data communication between functions

    The actualandformal arguments should match in number, type and order. The values of

    actual arguments are assigned to the formal arguments on a one to one basis, staring with

    the first arguments.

    Figure: Arguments matching between the function call and the called function

    Ensure that the function call has matching arguments. In case, the actual arguments are

    more than the formal arguments ( an > An ), the extra actual arguments are discarded. On

    the other hand, If the actual arguments are less than the formal arguments, the unmatched

    formal arguments are initialized to some garbage values. Any mismatch in data type may

    also result in passing of garbage values without generating the error message.

    Remember that, when a function call is made, only a copy of the values of actual

    arguments is passed into the called function. What occurs inside the function will have

    no effect on the variables used in the actual arguments list.

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 13 of 27

    main( )

    {

    . . . . . Actual Argumentsfunction-1 ( a1, a2,a3, . . . , a

    n) ;

    . . . . .}

    function-1( ){

    . . . . .

    function-1 ( A1, A2,A3, . . . , An) ;

    . . . . . Formal Arguments

    }

    FunctionCa

    ll

    CallingF

    unct i

    on

    Variable Number of ArgumentsVariable Number of Arguments

    Some functions have a variable number of arguments and data types which are not

    known at compile time (Example: printfandscanf functions). The ANSI standard

    proposes new symbol called the ellipsis to handle such functions. The ellipsis consists

    ofthree period(...)and used as double interest ( float p,)

    Both the function declaration and function definition should use ellipsis to indicate

    that the arguments are arbitrary both in number and type.

  • 8/3/2019 User Defined Udf

    14/27

    CS110/101 Algorithmic Approach to ProblemSolving

    Arguments with Return Values:To ensure a high degree of portability between programs, a function should generally be

    coded without involving any I/O operations. For instance, different programs may requiredifferent output formats fro display of results. This shortcoming can be overcome by

    handling over the result of a function to its calling function where the returned value can

    be used as required by the program. The self-contained and independent function should

    behave like a black boxthat receives a predefined form of input and outputs a desired

    value. Suchfunctions will have two-way data communication.

    Calling Function Called Function

    Figure: Two-way data communication between functions

    If we have mismatch between type of data that the called function returns and the type of

    data that the calling function expects, we will have unpredictable results. Be very careful

    to make sure that both types are compatible.

    No Argument but Returns a Value:There could be some situations where we may need to design functions that may not take

    any arguments but returns a value to the calling function. A typical example is the

    getchar library function declared in the header file .

    Example:

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 14 of 27

    Control / Values of Arguments

    Function Result /Return Value

    fucntion-1( )

    {

    . . . . .

    . . . . .

    z = function-2(a);

    . . . . .

    . . . . .

    }

    fucntion-2(x)

    {

    . . . . .

    . . . . .

    . . . . .

    . . . . .return ( y );

    }

    int getnum(void);

    main()

    {

    int m = get_num( ) ;

    printf(%d, m);

    }

    int get_num(void)

    {

    int n;

    scanf(%d, &n);

    return (n) ;

    }

  • 8/3/2019 User Defined Udf

    15/27

    CS110/101 Algorithmic Approach to ProblemSolving

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 15 of 27

  • 8/3/2019 User Defined Udf

    16/27

    CS110/101 Algorithmic Approach to ProblemSolving

    Functions that Returns Multiple Values:

    We have studied functions that return just one value using a return statement. That is

    because; a return statement can return only value. Suppose, however, that we want to get

    more information. We can achieve this in C using the arguments not only to receive

    information but also to send back information to the calling function. The arguments that

    are used to send out information are called output parameters.

    The mechanism of sending back information through arguments is achieved using the

    Address Operator ( & ) and Indirection Operator ( * ).

    Example: swapping the content of Two Numbers

    Calling Function Called Function

    Figure: Two-way data communication between functions

    The operator * is known as indirection operator because it gives an indirect reference toa variable through its address. The use of pointer variables as actual parameters forcommunicating data between functions is called Pass by Pointers or Call byPointers.

    Rules for Pass by PointersRules for Pass by Pointers

    1. The type of the actualandformalarguments must be same.

    2. The actual arguments (in the function call) must be the address of variables that

    are local to the calling function.Example: swapXY ( int &X, int &Y ) ;

    3. The formal arguments in the function header must be prefixed by the indirectionoperator* . Example: void swapXY ( int *X, int *Y ) { }

    4. In the prototype, the arguments must be prefixed by the symbol * . Example:

    void swapXY ( int *X, int *Y ) ; or void swapXY ( int*, int* ) ;

    5. To access the value of an actual argument in the called function, we must use the

    corresponding formal argument prefixed with the indirection operator* .Example: temp = *X ;

    *X = *Y ;

    *Y = temp ;

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 16 of 27

    #include

    void swapXY(int *x, int *y);

    main()

    {

    int x = 55 , y = 75 ;

    swapXY( &x, &y ) ;

    printf(%d %d, x, y );

    }

    void swapXY(int *a, int *b)

    {

    int temp ;

    temp = *a ;

    *a = *b ;

    *b = temp ;

    }

  • 8/3/2019 User Defined Udf

    17/27

    CS110/101 Algorithmic Approach to ProblemSolving

    Passing Parameters to Functions:

    The called function receives the information form the calling function through the

    parameters. The variables used while invoking the called function are called actual

    parameters. And the variables used in the function header of called function are called

    formal functions. There are two types of passing parameters to the functions:

    1. Pass by value ( Call by Value )

    2. Pass by Pointers (Call by Pointers / Address / Reference)

    Pass by Value (Call by Value): When a function is called with actual parameters, the

    values ofactual parameters are copied intoformal parameters. If the value of theformal

    parameters changes in the function, the values of the actual parameters are not changed.

    Note: In pass by value (call by value) any change done on formal parameters will not

    affect the actual parameters.

    Pass by Pointers / Address / Reference (Call by Pointers): In pass by reference, a

    function is called with address of actual parameters. In the function header, the formal

    parameters receives the address ofactual parameters. Now, the formal parameters do

    not contain values, instead they contain addresses. any variable that contains an address

    is called a pointer variable. Using pointer variables, the value of the actual parameters

    can be changed.

    Note: In pass by reference (call by reference) any change done on actual parameters

    indirectly using will affect the actual parameters. This way of changing the actual

    parameters using formal parameters is calledpass by reference or call by reference.

    Pass by ValuePass by Value versusversus Pass by PointersPass by Pointers(Call by Value(Call by Value versusversus Call by Reference/Pointers/Address)Call by Reference/Pointers/Address)

    The technique used to pass data from one function (Calling) to another (Called) function

    is known asparameter passing. There are two ways of parameter passing:

    1. Pass by Value ( or Call by Value )

    2. Pass by Pointers ( or Call by Pointers / References / Address )

    In Pass by Value ( or Call by Value ) , values of actual parameters are copied to the

    variables in the parameter (Formal) list of the called function. The called function works

    on the copy and not on the original values of the actual parameters. This ensures that the

    original data in the calling function cannot be changed accidentally.

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 17 of 27

  • 8/3/2019 User Defined Udf

    18/27

    CS110/101 Algorithmic Approach to ProblemSolving

    InPass by Pointers ( or Call by Pointers / References / Address ), the memory addresses

    of the variables rather than the copies of values are send to the called function. The called

    function directly works on the data in the calling function and the changed values are

    available in the calling function for its use. This method is used when manipulating

    arrays and strings. And also used when multiple values to be returned by the called

    function.

    Nesting of Functions:

    C permits nesting of functions freely. main can callfunction-1, which callsfunction-2,

    which callsfunction-3,. . .,and so on.there is in principle no limitas to how deeply

    functions can be nested. Nesting of function calls is also possible. For example:

    GCD = gcd( a, gcd( b , c) ); /* GCD of three integers */

    add_matrices ( add_matrices ( a, b ), c ); /* Sum of Three Matrices a, b & c */

    Note: The nesting dos not mean defining one function within another.

    Recursion: It is special case of process, where a function calls itself. It can be

    effectively used to solve problems, where solution is expressed in terms of successively

    applying the same solution to subsets of the problem. In recursive functions, we must

    have an ifstatement somewhere to force the function to return without the recursive call

    being executed. Otherwise, the function will never return.

    Example: Factorial of n = n(n-1)(n-2).1

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 18 of 27

    factorial ( int n ){

    int fact;

    if ( n == 1 )return (1);

    else

    fact = n * factorial ( n 1 ) ;

    return ( fact );

    }

  • 8/3/2019 User Defined Udf

    19/27

    CS110/101 Algorithmic Approach to ProblemSolving

    Passing Arrays to Functions:

    One-Dimensional Arrays:

    To pass a one-dimensional an array to a called function, it is sufficient to list the name of

    the array, without any subscripts, and the size of the array as arguments.

    Example: big = largest ( a, n) ; will pass the whole array a to the called function.

    The called function expecting this call must be appropriately defined. The largest

    function header might be int largest ( int array[] , int size )

    The declaration of the formal argument array is made as int array[];

    In C, the name of the array represents the address of its first element. By passing the

    array name, we are, in fact, passing the address of the array to the called function. The

    array in the called function now refers to the same array stored in the memory. Therefore,

    any change in the array in the called function will be truly reflected in the original array.

    Passing addresses of the parameters to the functions is referred to aspass by address or

    pass by pointers or pass by reference.

    Note: We cannot pass a whole array by value as we did in the case of ordinary variables.

    Rules to Pass an Array to a FunctionRules to Pass an Array to a Function

    1. The function must be called by passing only the name of the array.2. In the function definition, the formal parameter must be an array type; the size of

    the does not need to be specified.

    3. The function prototype must show the argument is an array.

    Two-Dimensional Arrays:

    Like simple arrays, we can also pass multi-dimensional arrays to functions. It is similar tothe one-dimensional arrays. The rules are simple.

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

    2. In the function definition, we must indicate that the array has two dimensions by

    including sets of brackets ( i.e., [] [] )

    3. The size of second dimension must be specified.

    4. The prototype declaration should be similar to the function header.

    Example:

    trace_matrix(a, m, n) ; /* Function Call */

    trace_matrix(int array[][n], int m, int n) /* Function Header / Function Definition */

    trace_matrix(int array[][n], int m, int n) /* Function Declaration / Prototype */

    Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06

    Page 19 of 27

  • 8/3/2019 User Defined Udf

    20/27

    CS110/101 Algorithmic Approach to ProblemSolving

    Passing Strings to Functions:

    The strings are treated as character arrays in C, the rules for passing strings to functions

    are very similar to those for passing arrays to functions. Like arrays, strings in C cannot

    be passed by values to functions.

    Example: void display ( char item_name[] ) /* Function Definition */

    void display ( char str[] ) ; /* Function Declaration */

    display ( names ) ; /* Function Call */where name must be properly declared in the calling function.

    char name [15] ;

    Programming Examples

    /*Program : B15.CWrite C User Defined Functions

    (i) To input N integer numbers into a single dimension array.(ii) To conduct a Linear Search.

    Using these functions, write a C program to accept the N integernumbers and given key integer number and conduct a Linear Search.Report success or failure in the form of a suitable message.

    */#include #include

    #define SIZE 10

    int a[SIZE]; /* Global Declaration */

    void input(int); /* Function Declaration / Prototype */void linear_search(int, int);/* Function Declaration / Prototype */

    main(){

    int n, key;clrscr();

    printf("\nEnter the size of list : ");scanf("%d", &n);

    input(n); /* Function Call, which reads N elements of the list */

    printf("\nEnter the key element to be searched in the list : ");scanf("%d", &key);

    linear_search(n,key);

    getch();}

    void input(int n) /* Function - input() */{

    int i;

    printf("\nEnter the %d elements : ",n);for(i=0 ; i

  • 8/3/2019 User Defined Udf

    21/27

    CS110/101 Algorithmic Approach to ProblemSolvingvoid linear_search(int n, int key) /* Function - linear_search() */{

    int i;

    for(i=0 ; i

  • 8/3/2019 User Defined Udf

    22/27

    CS110/101 Algorithmic Approach to ProblemSolving

    for(j=1 ; j

  • 8/3/2019 User Defined Udf

    23/27

    CS110/101 Algorithmic Approach to ProblemSolving

    /* Function call for Selection Sort */selection_sort(n);

    printf("\nThe Sorted elements using Selection Sort Method :");print_sorted(n);

    getch();}

    void print_sorted(int);

    void input(int n) /* Function - input() */{

    int i;

    for(i=0 ; i

  • 8/3/2019 User Defined Udf

    24/27

    CS110/101 Algorithmic Approach to ProblemSolving

    int i, n; /* Global Declaration */float x[10], sum, m, v, d; /* Global Declaration */

    void input(); /* Function Declaration / Prototype */float mean(); /* Function Declaration / Prototype */float varinace(); /* Function Declaration / Prototype */void sd(); /* Function Declaration / Prototype */

    main(){

    clrscr();

    printf("\nEnter the size of N : ");scanf("%d", &n);

    printf("\nEnter the %d real values to compute their Standard Deviation : \n",n);input(); /* Function to read N real numbers */

    sd(); /* Function call to compute Standard Deviation */getch();

    }

    /* Function to read N values */void input(){

    for(i=0 ; i

  • 8/3/2019 User Defined Udf

    25/27

    CS110/101 Algorithmic Approach to ProblemSolving

    /*Program : B19.CWrite C User Defined Functions:

    (a) To read the elements of a given matrix of size M x N.(b) To print the elements of a given matrix of size M x N.(c) To compute the product of two matrices.

    Using these functions, write a C program to read two matrices A(MxN) andB(PxQ) and compute the product of A and B after checking compatibilityfor multiplication. Output the input matrices and the resultant matrix

    with suitable headings and format.(Using two dimension arrays where array size M,N,P,Q

  • 8/3/2019 User Defined Udf

    26/27

    CS110/101 Algorithmic Approach to ProblemSolving{

    for(i=0; i

  • 8/3/2019 User Defined Udf

    27/27

    CS110/101 Algorithmic Approach to ProblemSolving

    a:printf("\nEnter the ROW number less than %d to find its Sum : ",m+1);scanf("%d",&row);if(row>m){

    printf("\nThe ROW number should not be greater than %d ",m);goto a;

    }rsum = row_sum(row,n);printf("\nSum of the elements of ROW-%d = %d\n",row,rsum);

    b:printf("\nEnter the COLUMN number less than %d to find its Sum : ",n+1);scanf("%d",&col);if(col>n){

    printf("\nThe COLUMN number should not be greater than %d ",n);goto b;

    }csum = col_sum(m,col);printf("\nSum of the elements of COLUMN-%d = %d\n",col,csum);trace = matrix_sum(m,n);printf("\nThe sum of all elements of the given MATRIX : %d",trace);getch();

    }void accept_matrix(int y, int z) /* Function to read MATRIX */{

    for(i=0; i