10 Functions – Programming in C, 3/e, 3rd Edition

CHAPTER 10

Functions

Chapter Outline
10.1  INTRODUCTION

It is difficult to prepare and maintain a large-sized program. Moreover, the identification of the flow of data is hard to understand. The best way to prepare a programming application is to divide the bigger program into small pieces or modules and the same modules can be repeatedly called from the main() function as and when required. These small modules or subprograms are easily manageable. This method is called the divide and conquer method. In C, such small modules are called functions. Figure 10.1 describes the method of developing a program.

Figure 10.1  A program divided in multiple functions

The programs written in the C language are highly dependent on functions. The C program is nothing but a combination of one or more functions. Every C program starts with the user-defined function main(). Each time when a new program is started, main() function must be defined. The main() function calls another functions to share the work. The main program can supply data to a function. A specific operation is performed on the data and a value is returned to the calling function.

The C language supports two types of functions: (1) library functions and (2) user-defined functions. The library functions are pre-defined set of functions. Their task is limited. A user should not worry to understand the internal working of these functions. One can only use the functions but cannot change or modify them. For example, sqrt (81) gives result 9. Here, the user need not worry about its source code, but the result should be provided by the function.

The user-defined functions are totally different. The functions defined by the user according to his/her requirement are called user-defined functions. A user can modify the functions according to the requirement. A user certainly understands the internal working of the function. The user has full scope to implement his/her own ideas in the function. Thus, the set of such user-defined functions can be useful to another programmer. One should include the file in which the user-defined functions are stored to call the function in the program. For example, let square(9) be a user-defined function that gives the result 81. Here, the user knows the internal working of the square() function, as its source code is visible. This is the major difference between the two types of functions.

10.2  BASICS OF A FUNCTION

A function is a self-contained block or a sub-program of one or more statements that perform a special task when called.

10.2.1  Why Use Functions?

  1. If we want to perform a task repetitively, then it is not necessary to re-write the particular block of the program again and again. Shift the particular block of statements in a user-defined function. The function defined can be called any number of times to perform the task.
  2. Using functions, large programs can be reduced to smaller ones. It is easy to debug and find out the errors in it. It also increases readability.

10.2.2  How a Function Works?

  1. Once a function is defined and called, it takes some data from the calling function and returns a value to the called function.
  2. The detail of inner working of a function is unknown to the rest of the program. Whenever a function is called, control passes to the called function and working of calling function is paused. When the execution of a called function is completed, control returns back to the calling function and executes the next statement.
  3. The values of actual arguments passed by the calling function are received by the formal arguments of the called function. The number of actual and formal arguments should be the same. Extra arguments are discarded if they are defined. If the formal arguments are more than the actual arguments, then the extra arguments appear as garbage. Any mismatch in the data type will produce the unexpected result.
  4. The function operates on formal arguments and sends back the result to calling function. The return() statement performs this task.
10.3  FUNCTION DEFINITION

Function definition is as per the format given below.

return_type function_name (argument/parameter list)

{

}

The following code illustrates the working of a function with its necessary components (Table 10.1).

Table 10.1  Working of a function

int abc (int, int, int);

void main( )

{

int x, y, z;

--------------------

--------------------

--------------------

--------------------

}

--------------------

--------------------

return(); return value

}

  1. The return type of the function can be int, float, double, char, void,etc., depending upon what is to be returned from called function to the calling function. By default in ANSI C, function returns int, if return type is not mentioned.
  2. Actual argument: The arguments of calling functions are actual arguments. In Table 10.1, variables ‘ x ’, ‘ y ’ and ‘ z ’ are actual arguments.
  3. Formal argument: The arguments of the called function are formal arguments. In Table 10.1, variables ‘ l ’, ‘ k ’ and ‘ j ’ are formal arguments.
  4. Function name: A function name follow the same rule as we use for naming a variable.

    Example:

    sum (int a, int b);

    where sum() is a user-defined function. This is a function call and ‘ a ’ and ‘ b ’ are integer arguments. The function call must be ended by a semi-colon (;).

  5. Argument/parameter list: The argument list means variable names enclosed within the parentheses. They must be separated by a comma (,). These formal arguments (consignment) receive values from the actual argument for performing the communication between consignee and consignor functions.
  6. Function call: A compiler executes the function when a semi-colon (;) is followed by the function name. A function can be called simply using its name like other C statement, terminated by a semi-colon (;).

Consider the following example.

   10.1  Write a program to show how user-defined function is called.

 

int add(int,int); /* function prototype */

void main ( )

{

int x=1,y=2,z;

z=add(x,y); /* FUNCTION call/

printf(“z=%d”,z);

}

/* FUNCTION DEFINITION */

int add(int a, int b)

{

return(a+b);

}

OUTPUT:

z=3

Explanation:

In the above program, values of ‘x’ and ‘y’ are passed to function add(). Formal arguments ‘a’ and ‘b’ receive the values. The function add() calculates the addition of both the variables and returns result. The result is collected by the variable ‘z’ of the main() function which is printed through the printf() statement.

   10.2  Write a program to define a user-defined function. Call them at different places.

 

void y();

void y()

{

printf(“Y”);

}

void main()

{

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

clrscr();

y();

a();

b();

c();

d();

}

void a()

{

printf(“A”);

y();

}

void b()

{

printf(“B”);

a();

}

void c()

{

a();

b();

printf(“C”);

}

void d()

{

printf(“D”);

c();

b();

a();

}

OUTPUT:

Y A Y B A Y A Y B A Y C D A Y B A Y C B A Y A Y

Explanation:

From the above program we can conclude that.

  1. The main() function can call any other function defined before or after the main() function.
  2. Any other user-defined function can call the main() function.
  3. The user-defined function can call only those user-defined functions which are defined before it, i.e. the function a() can call only y() and not b(), c() and d(). The function b() cannot call functions c() and d(). The function d() can call all the functions because it is the last function

    (f)Local and global variables: There are two kinds of variables: (i) local and (ii) global.

    (i)Local variable: The local variables are defined within the body of the function or block. The variable defined is local to that function or block only. Other functions cannot access these variables. The compiler shows errors in case other functions try to access the variables.

Example:

value(int k, int m)

{

int r,t;

}

Here ‘r’ and ‘t’ are the local variables, which are defined within the body of the function value(). The same variable names may be defined in different functions. They are local to that particular function.

Programs on local and global variables are illustrated below.

   10.3  Write a program to show how similar variable names can be used in different functions.

 

void fun(void);

void main()

{

int b=10,c=5;

clrscr();

printf(“\n In main() B=%d C=%d”,b,c);

fun();

}

void fun()

{

int b=20,c=10;

printf(“\nIn fun() B=%d C=%d”,b,c);

}

OUTPUT:

In main() B=10 C=5

In fun()B=20 C=10

Explanation:

In the above program, two functions are used. One is main() and the other user-defined function is fun(). The variables ‘b’ and ‘c’ are defined in both the functions. Their effect is only within the function in which they are defined. Both the functions print local values of ‘b’ and ‘c’ assigned in their functions.

We can also declare the same variable names for actual and formal arguments. The compiler will not get confused due to same variable names. The scope of every auto variable is local to the block in which they are defined.

 

(ii) Global variables: Global variables are defined outside the main() function. Multiple functions can use them. The example is illustrated below for understanding.

   10.4  Write a program to show the effect of global variables on different functions.

 

void fun(void);

int b=10,c=5;

void main()

{

clrscr();

printf(“\nIn main() B=%d C=%d”,b,c);

fun();

b++;

c−−;

printf(“\n Again In main() B=%d C=%d”,b,c);

}

void fun()

{

b++;

c−−;

printf(“\n In fun() B=%d C=%d”,b,c);

}

OUTPUT:

In main()

B=10 C=5

In fun()

B=11 C=4

Again In main()

B=12 C=3

Explanation:

In the above program, variables ‘b’ and ‘c’ are defined outside the main(). Hence, they are global. They can be called by any other function. The same variables ‘b’ and ‘c’ are used throughout the program. In main(), values of ‘b’ and ‘c’ are printed.

The function fun() is called; ‘b’ is incremented and ‘c’ is decremented. The values of ‘b’ and ‘c’ are printed. The control then returns to the function main().

Again ‘b’ is incremented and ‘c’ is decremented. The values of ‘b’ and ‘c’ are printed. Here,both the functions use the same variables.

 

(g)Return value: It is the outcome of the function. The result obtained by the function is sent back to the calling function through the return statement. The return statement returns one value per call. The value returned is collected by the variable of the calling function.

10.4  THE return STATEMENT

The user-defined function uses the return statement to return the value to the calling function. Exit from the called function to the calling function is done by the use of the return statement. When the return statement is executed without argument, it always return 1.

   10.5  Write a program to use the return statement in different ways.

 

int pass(int);

void main()

{

int x,y;

clrscr();

printf(“Enter value of x :”);

scanf(“%d”,&x);

if(x==1 || x<0)

return 0;

y=pass(x);

switch(y)

{

  case 1:

  printf(“The value returned is %d”,y);

  break;

  default :

  printf(“The Cube of %d is : %d”,x,y);

}

return 0;

}

int pass(a)

{

if(a==0)

return 0;

else

return(a*a*a);

}

OUTPUT:

Enter value of x : 5

The Cube of 5 is :125

  1. return 0: This statement returns zero to the operating system if the value entered by the user is 1 or negative.
  2. return: The value of ‘x’ is passed to the function pass(). If the value is zero then the return statement returns 1.The return statement is used to exit from the function pass().
  3. return (a*a*a): In a function pass(), when the if statement finds the value of ‘x’ as non-zero then else block is executed and the return statement returns the cube of the entered number.

The return statement can be used in the following ways.

  1. return(expression);

    Example:

    return(a+b+c);

    If such a statement is executed, the expression within the parentheses is first solved and the result obtained is returned.

  2. A function may use one or more return statements. It is used when we want to return a value depending upon certain conditions.

    Example:

    The if statement

     

    if(a>b)

    The switch()statement

    return(a);

    switch(x)

    else

    {

    return(b);

    case 1 :

     

    return(1);

     

    break;

     

    case 2

     

    return(1*2);

     

    break;

     

    default :

     

    return(0);

     

    }

  3. return(&p);

    If above syntax is used, it returns the address of the variable.

  4. return(*p);

    The above statement returns the value of a variable through the pointer.

  5. return(sqrt(r));

    If such a format is used, when control reaches to the return statement, control again passes to function sqrt(). The return statement collects the result obtained from sqrt() function and returns it to the calling function. Here, the return statement calls the function sqrt().

  6. return(float(square(2.8));

    All functions return by default integer value. To force the function return other type of value, specify the data type to be used. When a value is returned, it automatically converts to the function data type. In the above example, the return value will be converted to float type.

    From the above discussion we can conclude the following:

  1. When the return statement is encountered in the function the control sends back to the calling function and next statement following return statement if present will not be executed.
  2. The absence of the return statement indicates that no value is returned. Such functions are called a void.
10.5  TYPES OF FUNCTIONS

Depending on arguments present, the return value sends the result back to the calling function. Based on this, the functions are divided into four types.

  1. Without arguments and return values (see Table 10.2).

    Table 10.2  Functions without arguments and return values

    Calling Function

    Analysis

    Called Function

    void main()

     

    abc()

    {

     

    {

    ----------------------

     

    ----------------------

    ----------------------

     

    ----------------------

    abc();

    No arguments are passed

    ----------------------

    ----------------------

    No values are sent back.

    }

    ----------------------

     

     

    }

     

     

    1. Data is neither passed through the calling function nor sent back from the called function.
    2. There is no data transfer between calling and called functions.
    3. The function is only executed and nothing is obtained.
    4. If such functions are used to perform any operation, they act independently. They read data values and print result in the same block.
    5. Such functions may be useful to print some message, draw a line or spilt the line.

    Example:

       10.6  Write a program to display a message using user-defined function.

     

    void main()

    {

    void message();

    message();

    }

    void message()

    {

    puts(“Have a nice day”);

    }

    OUTPUT:

    Have a nice day

    Explanation:

    This program contains a user-defined function named message(). It requires no arguments and returns nothing. It displays only a message when called.

       10.7  Write a program to display alphabets ‘A’ , ‘B’ and ‘C’ using functions.

     

    void main()

    {

    void a(), b(),c();

    a();

    b();

    c();

    }

    void a()

    {

    printf(“\nA”);

    }

    void b()

    {

    printf(“B”);

    }

    void c()

    {

    printf(“C”);

    }

    OUTPUT:

    ABC

    Explanation:

    In the above example, three user-defined functions a(), b() and c() are defined. The main() function calls these three functions. These functions get called as per the calling sequence and messages are displayed.

  2. With arguments but without return values (Table 10.3).

    Table 10.3  Function with arguments but without return values

    Calling Function

    Analysis

    Called Function

    void main()

     

    abc(y)

    {

     

    {

    ----------------------

     

    ----------------------

    ----------------------

     

    ----------------------

    abc(x);

    Argument(s) are passed.

    ----------------------

    ----------------------

    No values are sent back.

    }

    ----------------------

     

     

    }

     

     

    1. In the above functions, arguments are passed through the calling function. The called function operates on the values. But no result is sent back
    2. Such functions are partly dependent on the calling function. The result obtained is utilized by the called function and there is no gain to the main().

    Example:

       10.8  Write a program to pass date, month and year as parameters to a user-defined function and display the day in the format dd/mm/yy.

     

    # include<stdio.h>

    # include<conio.h>

     

    void main()

    {

    int dat(int ,int ,int );

    int d,m,y;

    clrscr();

    printf(“\nEnter Date: dd/mm/yy”);

    scanf("%d %d %d",&d,&m,&y);

    dat(d,m,y);

    getch();

    }

     

    int dat(int x, int y, int z)

    {

    printf(“\nDate = %d/%d/%d",x,y,z);

    return 0;

    }

    OUTPUT:

    Enter Date: dd/mm/yy09 09 2014

    Date = 9/9/2014

    Explanation:

    In this program, three value are passed to the dat() function. The dat() function receives arguments form main() and displays date. But it returns nothing.

       10.9  Write a program to calculate square of a number using user-defined function.

     

    void main()

    {

    int j=0;

    void sqr(int);

    clrscr();

    for(j=1;j<5;j++)

    sqr(j);

    }

    void sqr(int k)

    {

    printf("\n%d", k*k);

    }

    OUTPUT:

    1

    4

    9

    16

    Explanation:

    Here, in this program, the main() function passes one argument per call to the function sqr(). The function sqr() collects this argument and prints its square. The function sqr() is void.

       10.10  Write a program to pass the value to main() function.

     

    void main(int j)

    {

    clrscr();

    printf(“\n Number of command line arguments J = %d”,j);

    }

    Explanation:

    To execute this program, first create its executable file and execute the program from the command prompt. The above example illustrates the command line arguments.

    C:\> main.exe 1 2 3

    In the above example, main.exe is the file name containing the program code. The file is executed from the command prompt. Following the file name some arguments are written. The variable ‘j’ contains the number of arguments supplied from the command prompt. Here, four arguments are supplied to the file name. Thus, the main() function receives the arguments and returns nothing.

  3. With arguments and return values (Table 10.4).

    Table 10.4  Function with arguments and return values

    void main()

     

    abc(y)

    {

     

    {

    int z;

     

    -----------

    -----------

     

    y++;

    z=abc(x);

     Argument(s) are passed.

    -----------

    -----------

     

    -----------

    -----------

    Values are sent back.

    -----------

    }

     

    return(y);

     

     

    }

    1. In the above example, the copy of the actual argument is passed to the formal argument, i.e. the value of ‘x’ is assigned to ‘y’.
    2. The return statement returns the incremented value of ‘y’. The returned value is collected by ‘z’.
    3. Here, data is transferred between calling and called functions, i.e. communication between functions is made.

       10.11  Write a program to pass values to a user-defined function and display the date, month and year.

     

    # include <stdio.h>

    # include <conio.h>

     

    void main()

    {

    int dat(int ,int ,int );

    int d,m,y,t;

    clrscr();

    printf(“Enter Date dd/mm/yy : “);

    scanf(“%d %d %d”,&d,&m,&y);

    t=dat(d,m,y);

    printf(“\nTomorrow = %d/%d/%d”,t,m,y);

    getch();

    }

     

    int dat(int x, int y, int z)

    {

    printf(“\nToday= %d/%d/%d”,x,y,z);

    return(++x);

    }

    OUTPUT:

    Enter Date dd/mm/yy : 09 09 2014

    Today= 9/9/2014

    Tomorrow = 10/9/2014

    Explanation:

    In the above program, three values date, month and year are passed to the function dat().The function displays date. The function dat() returns the next date. The next date is printed in function main(). Here, function dat() receives arguments and return values.

       10.12  Write a program to send values to user-defined function and receive and display the return value.

     

    int main()

    {

    int sum(int,int,int), a,b,c,s;

    clrscr();

    printf(“Enter Three Numbers :”);

    scanf(“%d %d %d”, &a,&b,&c);

    s=sum(a,b,c);

    printf(“Sum = %d”,s);

    return 0;

    }

    int sum(int x, int y, int z)

    {

    return(x+y+z);

    }

    OUTPUT:

    Enter Three Numbers : 7 5 4

    Sum = 16

    Explanation:

    In the above program, the function sum() receives three values from the function main(). The sum() calculates the sum of three numbers and returns them to main().

  4. Without arguments and but with return values (Table 10.5)

    Table 10.5  Functions without arguments but with return values

    main()

     

    abc()

    {

     

    {

    int z;

     

    int y=5;

    -----------

     

    -----------

    z=abc();

     No Argument(s) are passed.

    -----------

    -----------

     

    -----------

    -----------

    Values are sent back.

    return(y);

    }

     

    }

     

    1. In the above type of function, no argument(s) is passed through the main() function. But the called function returns values.
    2. The called function is independent. It reads values from keyboard or generates from initialization and returns the values.
    3. Here, both the calling and called functions partly communicate with each other.

       10.13  Write a program to receive values from user-defined function without passing any value through main().

     

    int main()

    {

    int sum(),a,s;

    clrscr();

    s=sum();

    printf(“Sum = %d”,s);

    return 0;

    }

    int sum()

    {

    int x,y,z;

    printf(“\n Enter Three Values :”);

    scanf(“%d %d %d”,&x,&y,&z);

    return(x+y+z);

    }

    OUTPUT:

    Enter Three Values : 3 5 4

    Sum = 12

    Explanation:

    The user-defined function sum() is an independent function. The function sum() reads three values through the keyboard and returns their sum to the function main(). The main() only prints the sum.

       10.14  Write a program to read values through the user-defined function and send back the result in the form of an address.

     

    int main()

    {

    int *sum(),*s;

    clrscr();

    s=sum();

    printf(“Sum = %d”,*s);

    return 0;

    }

    int *sum()

    {

    int x,y,z,k;

    printf(“\nEnter Three Values :”);

    scanf(“%d %d %d”,&x,&y,&z);

    k=x+y+z;

    return(&k);

    }

    OUTPUT:

    Enter Three Values : 1 3 5

    Sum = 9

    Explanation:

    The function sum() is declared as a pointer function, i.e. the function declared as a pointer always returns reference. The reference returned by the function sum() is assigned to pointer *s. The pointer *s prints the sum.

10.6  CALL BY VALUE AND REFERENCE

There are two ways in which we can pass arguments to the function.

  1. Call by value: In this type, the value of actual arguments is passed to the formal arguments and operation is done on the formal arguments. Any change in the formal argument made does not affect the actual arguments because formal arguments are the photocopy of the actual argument. Hence, when a function is called by the call by value method, it does not affect the actual contents of the arguments. Changes made in the formal arguments are local to the block of the called function. Once control returns back to the calling function, changes made vanish. The example given below illustrates the use of call by value.

       10.15  Write a program to exchange values of two variables by using ‘call by value’ to the function.

     

    int main()

    {

    int x,y,change (int, int);

    clrscr();

    printf(“\n Enter Values of X & Y :”);

    scanf(“%d %d”,&x,&y);

    change(x,y);

    printf(“\n In main() X=%d Y=%d”,x,y);

    return 0;

    }

    change(int a, int b)

    {

    int k;

    k=a;

    a=b;

    b=k;

    printf(“\n In Change() X=%d Y=%d”,a,b);

    }

    OUTPUT:

    Enter Values of X & Y : 5 4

    In Change() X=4 Y=5

    In main()X=5 Y=4

    Explanation:

    In the above program, we are passing values of actual argument ‘x’ and ‘y’ to the function change(). The formal arguments ‘a’ and ‘b’ of function change() receive these values(). The values are interchanged, i.e. the value of ‘a’ is assigned to ‘b’ and vice versa and printed. When the control returns back to the main(), the changes made in the function change() vanish. In the main(), the values of ‘x’ and ‘y’ are printed as they read from the keyboard. In the call by value method, the formal argument acts as a photocopy of the actual argument. Hence, changes made to them are temporary.

  2. Call by reference: In this type, instead of passing values, addresses (reference) are passed. Function operates on addresses rather than values. Here, the formal arguments are pointers to the actual argument. In this type, formal arguments point to the actual argument. Hence, changes made in the argument are permanent. The example given below illustrates the use of call by value.

       10.16  Write a program to send a value by reference to the user-defined function.

     

    int main()

    {

    int x,y,change (int*, int*);

    clrscr();

    printf(“\n Enter Values of X & Y :”);

    scanf(“%d %d”,&x,&y);

    change(&x,&y);

    printf(“\n In main() X=%d Y=%d”,x,y);

    return 0;

    }

    change(int *a, int *b)

    {

    int *k;

    *k=*a;

    *a=*b;

    *b=*k;

    printf(“\n In Change() X=%d Y=%d”,*a,*b);

    }

    OUTPUT:

    Enter Values of X & Y : 5 4

    In Change() X=4 Y=5

    In main()X=4 Y=5

    Explanation:

    In the above example, we are passing addresses of formal arguments to the function change(). The pointers in the change() receive these addresses, i.e. pointer points to the actual argument. Here, the change()function operates on the actual argument through the pointer. Hence, the changes made in the values are permanent. In this type of call, no return statement is required.

10.7  FUNCTION RETURNING MORE VALUES

So far, we know that the function can return only one value per call. We can also force the function to return more values per call. It is possible by the call by reference method. The given below example illustrates this fact.

   10.17  Write a program to return more than one value from the user-defined function.

 

int main()

{

int x,y,add,sub,change (int*, int*, int*, int*);

clrscr();

printf(“\n Enter Values of X & Y :”);

scanf(“%d %d”,&x,&y);

change(&x,&y,&add,&sub);

printf(“\n Addition : %d ”,add);

printf(“\n Subtraction : %d ”,sub);

return 0;

}

change(int *a, int *b,int *c,int *d)

{

*c=*a+*b;

*d=*a−*b;

}

OUTPUT:

Enter Values of X & Y : 5 4

Addition : 9

Subtraction : 1

Explanation:

In this program the return statement is not used. Still function returns more than one value. Actually, no values are returned. Once the addresses of variables are available, we can directly access them and modify their contents. Hence, in the call by reference method, it is possible to directly modify the contents of the variable. The memory addresses of the variables are unique. There is no scope rule for memory address. If we declare the same variable for actual and formal arguments, their memory addresses will be different from each other.

   10.18  Write a program to pass arguments to the user-defined function by value and reference.

 

int main()

{

int k,m,other(int,int*);

clrscr();

printf(“\n Address of k & m in main() : %u %u”,&k,&m);

other(k,&m);

return 0;

}

other(int k,int *m)

{

printf(“\n Address of k & m in other() : %u %u”,&k,m);

}

OUTPUT:

Address of k & m in main():65524 65522

Address of k & m in other() :65518 65522

Explanation:

In the above example, we are passing value as well as reference; therefore it is a mix-call i.e. calls by value and reference. The first variable is passed by the call by value method and second by reference.

  1. The variable ‘k’ of the functions other() and main() is different from each other. The compiler treats them different. Hence, their memory addresses are different.
  2. We are passing the address of variable ‘m’. It is received by the pointer ‘m’ of the other() function, i.e. pointer ‘m’ of function other() contains the memory location of variable ‘m’of main(). The pointer ‘m’ points to variable ‘m’. Hence, the address printed of ‘m’ is the same as in main(). This is the difference between these two calls.
10.8  FUNCTION AS AN ARGUMENT

Till now we passed values or address through the functions. It is also possible to pass a function as an argument.

   10.19  Write a program to pass a user-defined function as an argument to another function.

 

#include<stdio.h>

#include<conio.h>

int doub(int m);

int square(int k);

void main()

{

int y=2,x;

clrscr();

x=doub(square(y));

printf(“x=%d”,x);

}

int doub(int m)

{

int p;

p=m*2;

return(p);

}

int square(int k)

{

int z;

z=k*k;

return(z);

}

OUTPUT:

x=8

Explanation:

In the above example, instead of passing a variable or its address, a function is passed as an argument. The innermost function square() is executed first and completed. Its return value is collected by the doub() function. The doub() function uses the square() function as an argument. It operates on the return value of square() function and makes the returned value double and returns to the main() function.

   10.20  Write a program to use two functions as arguments for another function.

 

# include <math.h>

int main()

{

int d,x(int,int),y(),z();

d=x(z(), y());

printf(“\n z() − y()= %d”,d);

return 0;

}

int x(int a, int b)

{

return(abs(a−b));

}

int y()

{

int y;

clrscr();

printf(“\n Enter First Number : ”);

scanf(“%d”,&y);

return(y);

}

int z()

{

int z;

printf(“\n Enter Second Number : ”);

scanf(“%d”,&z);

return(z);

}

OUTPUT:

Enter First Number : 25

Enter Second Number : 50

z() − y()= 25

Explanation:

The above program consists of three user-defined functions x(), y() and z(). The functions z() and y() are passed through the function x(), i.e. they are used as arguments. They read values and return to function x(). The function x() carries subtraction and return to main(). The variable ‘d’ prints difference between these two values. The abs() function is called through the return() statement to return only the positive value.

Note: abs() function returns absolute value of a given number.

Below given program can be used in place of the abs() function. It is a user-defined function, we call it as uabs().‘U’ stands for user-defined.

   10.21  Write a program to return only the absolute value like the abs() function.

 

int main()

{

int uabs(int),x;

clrscr();

printf(“Enter a Value :”);

scanf(“%d”,&x);

x=uabs(x);

printf(“\n X= %d”,x);

return 0;

}

int uabs(int y)

{

if(y<0)

return( y * −1);

else

return(y);

}

OUTPUT:

Enter a Value : −5

X = 5

Working of uabs() function.

The uabs() function receives values from the calling function. If the value is less than zero (0), i.e. negative, it is multiplied by −1 to make it absolute, otherwise it returns as it is.

   10.22  Write a program to calculate square and cube of an entered number. Use function as an argument.

 

# include <math.h>

int input();

int sqr(int m);

int cube(int m);

void main()

{

int m;

clrscr();

printf(“\n\tCube : %d”,cube(sqr(input())));

}

int input()

{

int k;

printf(“Number :”);

scanf(“%d”,&k);

return k;

}

int sqr(int m)

{

printf(“\tSquare : %d”,m*m);

return m;

}

int cube(int m)

{

return m*m*m;

}

OUTPUT:

Number : 2

Square : 4

Cube : 8

Explanation:

In the above program, three user-defined functions are defined. They are input(), sqr() and cube().

  1. The function input() prompts user to enter a number.
  2. The function sqr() calculates the square of the entered number.
  3. The function cube() calculates the cube of the entered number.

In the printf() statement, the input() function is used as an argument of sqr() function and again the function sqr() is used as an argument for the cube() function. These functions work as given below.

The function input() is executed first. It prompts the user to enter a number. The function input() returns the value which is the entered number. The return value of input() function is passed to the function sqr() and square is calculated. The sqr() function returns the number and it is passed to the function cube(). The function cube() calculates the cube of the original number.

10.9  FUNCTION WITH OPERATORS

The below given program illustrates the use of various operators with a function.

  1. The assignment operator (=): The use of this operator is to assign some value to the variable. To assign return value of function to the variable following syntax is used.

    Syntax:

    x=sqr(2);

    where ‘x’ is a variable and sqr() is a user-defined function. The value returned by the the sqr() function is assigned to variable ‘x’.

       10.23  Write a program to assign the return value of a function to another variable.

     

    void main()

    {

    int input(int);

    int x;

    clrscr();

    x=input(x);

    printf(“\nx=%d”,x);

    }

    int input(int k)

    {

    printf(“\nEnter Value of x =”);

    scanf(“%d”,&k);

    return(k);

    }

    OUTPUT:

    Enter Value of x = 5

    x = 5

    Explanation:

    In the above program, the user-defined function input() reads integer value through the keyboard. The read value is returned to the main() function. The variable ‘x’ in the main()function collects the returned value. The printf() statement prints the value of ‘x’.

  2. Addition and Subtraction (+ & −):

    Syntax:

    x=(1−fun()+1);

    where ‘x’ is an integer and fun() is a user-defined function.

       10.24  Write a program to perform the addition and subtraction of numbers with the return value of function.

     

    # include <math.h>

    void main()

    {

    int input(int);

    int sqr(int);

    int x;

    clrscr();

    x=sqr(1−input(x)+1);

    printf(“\nSquare = %d”,x);

    }

    int input(int k)

    {

    printf(“\nEnter Value of x =”);

    scanf(“%d”,&k);

    return(k);

    }

    int sqr(int m)

    {

    return(pow(m,2));

    }

    OUTPUT:

    Enter Value of x = 5

    Square = 9

    Explanation:

    In the above program, two user-defined functions are defined. The input() function reads the number through the keyboard. The sqr() function calculates the square of the number. The input() function is an argument of sqr() function.

    The value returned by input() is subtracted from 2. Though we used ‘−’ operator only once; the equation built is 1−5+1. The number 5 is the returned value of input(). The subtraction takes place two times. Hence, two times one is subtracted and instead of 5, the sqr() function receives number −3. Hence, square of −3 is 9.

  3. Multiplication and Division (* & /):

       10.25  Write a program to perform multiplication and division of numbers with return value of function.

     

    # include <math.h>

    void main()

    {

    int input(int);

    int sqr(int);

    int x;

    clrscr();

    x=sqr(5*input(x)/2);

    printf(“\nSquare = %d”,x);

    }

    int input(int k)

    {

    printf(“\nEnter Value of x =”);

    scanf(“%d”,&k);

    return(k);

    }

    int sqr(int m)

    {

    return(pow(m,2));

    }

    OUTPUT:

    Enter Value of x = 5

    Square = 144

    Explanation:

    The above program is the same as the previous one. Instead of addition and subtraction operations, multiplication and division operations are performed

  4. Increment and Decrement Operators ( ++ & −− ): The uses of these operators are to increment or decrement the value of the variable. Here, they perform the same job with the return value of functions.

    Syntax:

    x=fun1(++(y=(fun2 (x))));

    where ‘x’ and ‘y’ are integer and fun1() and fun2() are functions.

    Consider the example following example.

       10.26  Write a program to use (++) operator with the return value of a function.

     

    # include <math.h>

    void main()

    {

    int input(int);

    int sqr(int);

    int x,y=0;

    clrscr();

    x=sqr(++(y=(input(x))));

    printf(“\n Square = %d”,x);

    }

    int input(int k)

    {

    printf(“\n Enter Value of x =”);

    scanf(“%d”,&k);

    return(k);

    }

    int sqr(int m)

    {

    return(pow(m,2));

    }

    OUTPUT:

    Enter Value of x = 7

    Square = 64

    Explanation:

    In the above example, the returned value of input() function is first incremented and passed to the function sqr(). The sqr() function gives the square of incremented value. We cannot apply these operators (++ and −−) directly to the function. We used an extra variable ‘y’. The value returned is collected in variable ‘y’ and then ‘y’ is incremented.

    Note: The decrement (−−) operator works in the same way. It decrements the value.

  5. Mod (%) and ? Operators.

       10.27  Write a program to use mod (%) with function.

     

    int main()

    {

    int j();

    if(j()%2==0)

    printf(“\n Number is Even.”);

    else

    printf(“\n Number is Odd.”);

    return 0;

    }

    int j()

    {

    int x;

    clrscr();

    printf(“\n Enter a Number :”);

    scanf(“%d”,&x);

    return(x);

    }

    OUTPUT:

    Enter a Number : 5

    Number is Odd.

    Explanation:

    In the above program, the mod operation is directly applied to return the value of function j(). The function j() reads the number through the keyboard and returns it to main(). If the remainder is ‘0’, the number is even, otherwise it is odd.

       10.28  Write a program to use conditional operator (?) with function.

     

    # include <math.h>

    int main()

    {

    int x,y(),z, sqr(int),cube(int);

    clrscr();

    printf(“\n Enter a Number :”);

    scanf(“%d”,&x);

    z=(x>y() ? sqr(x) : cube(x));

    printf(“= %d”,z);

    return 0;

    }

    int sqr(int x)

    {

    printf(“Square”);

    return(pow(x,2));

    }

    int cube(int x)

    {

    printf(“Cube”);

    return(pow(x,3));

    }

    int y()

    {

    return(10);

    }

    OUTPUT:

    Enter a Number : 5

    Cube = 125

    Explanation:

    There are three user-defined functions in this example. They are y(), sqr() and cube().The return value of function y() is compared with value entered by the user, i.e. ‘x’. The condition is given in the ternary operator. The ternary operator decides which function to call depending on the condition. If (x > y()) condition is true, i.e. ‘x’ is larger the function sqr() is called, otherwise function cube() is called. The user-defined functions can be used with (< and >). Here, the function y() is used.

       10.29  Write a program to compare two return values of functions.

     

    int main()

    {

    int a(),b();

    clrscr();

    if(a()==b())

    printf(“\n Value of a() & b() are equal.”);

    else

    printf(“\n Value of a() & b() are unique.”);

    return(0);

    }

    int a()

    {

    int x;

    printf(“\n Enter a Number a() :”);

    scanf(“%d”,&x);

    return(x);

    }

    int b()

    {

    int x;

    printf(“\n Enter a Number b() :”);

    scanf(“%d”,&x);

    return(x);

    }

    OUTPUT:

    Enter a Number a() : 5

    Enter a Number b() : 5

    Value of a() & b() are equal.

    Explanation:

    Here, a() and b() are two user-defined functions. They read values through the keyboard and return to main() function. Both functions are called from the if() statement. First, a() is called. It reads an integer. Similarly, b() is called to perform the same task as a(). The if statement compares both return values and displays proper message.

  6. Arithmetic equations

       10.30  Write a program to evaluate the equation s=sqr(a()+b()) using function.

     

    int main()

    {

    int s=0,a(),b(),sqr(int);

    clrscr();

    s=sqr(a()+b());

    printf(“\n Square of Sum = %d”,s);

    return 0;

    }

    int a()

    {

    int a;

    printf(“\n Enter value of a :”);

    scanf(“%d”,&a);

    return(a);

    }

    int b()

    {

    int b;

    printf(“\n Enter value of b :”);

    scanf(“%d”,&b);

    return(b);

    }

    int sqr(int x)

    {

    return (x*x);

    }

    OUTPUT:

    Enter value of a : 5

    Enter value of b : 3

    Square of Sum = 64

    Explanation:

    In the above program, functions a() and b() read integer ‘a’ and ‘b’ through the input device. The returned values of these function are added and this addition is passed to function sqr() to obtain the square the sum.

       10.31  Write a program to evaluate the equation y=x1+x2+ ... xn using function.

     

    #include<math.h>

    int main()

    {

    int b(),x,y=0,z=0,n,a;

    clrscr();

    printf(“Values of ‘x’ and ‘n’: ”);

    scanf(“%d %d”,&x,&n);

    while(z++!=n)

    {

      a=pow(x,b());

      y=y+a;

      printf(“%d +”,a);

      if(z==n)

      {

        printf(“\n Value of y = %d”,y);

        return 0 ;

      }

    }

    return 0;

    }

    int b()

    {

    static int m;

    return(++m);

    }

    OUTPUT:

    Values of ‘x’ and ‘n’ : 3 3

    3 + 9 + 27 +

    Value of y = 39

    Explanation:

    In the above example, the statement y=y+pow(x, b()) within the while loop evaluates the series. The pow() function calculates the power of ‘x’ by returned value of function b(). The function b() is called for ‘n’ times. During each call, the value of variable ‘m’ is incremented by one. The variable ‘m’ is declared as static. The value of variable ‘m’ does not vanish when the function is not active.

10.10  FUNCTION AND DECISION STATEMENTS

There are two ways to use decision-making statements in C.

  1. Use of if ... else statement. For syntax see Table 10.6

    Table 10.6   if else statement with & without function

    Without Function

    With Function

    if(condition)

    if(fun())

    Statement1;

    statement1;

    else

    else

    Statement1;

    statement2;

    }

    where fun() is a function.

    The if ... else statement is used to make the decision in the program at the run time. It decides which statement to execute and which statement to bypass, depending up certain conditions.

    The above syntax is used commonly in the program.

    Here, in this example, instead of writing condition directly, we are passing function. Here, when the if() statement executes control is passed in the function fun(). The return value of function is used for condition.

       10.32  Write a program to call user-defined function through the if statement.

     

    void main()

    {

    int a();

    clrscr();

    if(a()%2==0)

    printf(“\n The number is even.”);

    else

    printf(“\n The Number is odd.”);

    }

    int a()

    {

    int a;

    printf(“\n Enter value of a :”);

    scanf(“%d”,&a);

    return(a);

    }

    OUTPUT:

    Enter value of a : 5

    The Number is odd.

    Explanation:

    In the above program, a() reads number from terminal and sends it to the main() function. The mod operation is done on the return value. If the result of mod operation is zero then the message printed is ‘The number is even’ otherwise ‘The number is odd’. Thus, in this example the returned value of function is directly used for operation.

  2. switch...case statement: The switch case statement also makes decision at run time in the program. It has multiple choices. The switch() requires one argument and its body contains various case statements like branch. Depending upon the value of the switch argument matched case statement is executed. Syntax of switch with and without function is as per Table 10.7.

    Syntax:

    Table 10.7  Function and swtich() statements

    Without Function

    With function

    switch(x)

    switch(b())

    {

    {

    case 1:

    case 1:

    -----

    -----

    break;

    break;

    case 2:

    case 2:

    ------

    ------

    break;

    break;

    default:

    default:

    }

    }

    where ‘x’ is an argument of any data type.

    where b() is a function

     

       10.33  Write a program to call user-defined function through the swtich() statement.

     

    # include <math.h>

    # include <ctype.h>

    void main()

    {

    int a();

    int x=5;

    clrscr();

    switch(a())

    {

      case ‘s’ :

      printf(“\n Square of %d is %d”,x,pow(x,2));

      break;

      case ‘c’ :

      printf(“\n Cube of %d is %d”,x,pow(x,3));

      break;

      case ‘d’ :

      printf(“\n Double of %d is %d”,x,x*2);

      break;

      default :

      printf(“\n Unexpected Choice printed as it is : %d”, x);

    }

    }

    int a()

    {

    char c=‘’;

    printf(“Enter Your Choice Square(s),Cube(c),Double(d) : ”);

    c=getche();

    c=tolower(c);

    return(c);

    }

    OUTPUT:

    Enter Your Choice Square(s),Cube(c),Double(d) : D

    Double of 5 is 10

    Explanation:

    In the above example, value ‘5’ is assigned to variable ‘x’. Here, the function is called from the switch() statement. It prompts the user to enter choice. The choice entered by the user is returned to the switch() statement. Depending upon this value, matching case statement is executed. In the shown output, user pressed ‘D’. The swich() case executes double operation.

10.11  FUNCTION AND LOOP STATEMENTS

Loop statements are used to repeat program code repetitively for a given number of times or based on certain conditions.

  1. The for loop
  2. The while loop
  3. The do..while loop

1.  Working with for loop: The syntax of for with & without function is as per Table 10.8.

Table 10.8  Function and for loop

Without Function

With Function

for(starting value; stop value; step)

for(fun(); fun1(); fun2())

OR

 

for(initial value; condition,increment/decrement)

where, fun(), fun1() and fun2() are user-defined functions

These are common syntax of the for loop statement.

In the above example, at every step of for loop we are using user-defined function, i.e. when such statement executes iterations are completed calling the functions.

  1. Working with for loop :

       10.34  Write a program to call function through the for loop.

     

    # include <process.h>

    void main()

    {

    int plus(int),m=1;

    clrscr();

    for(;plus(m);m++)

    {

      printf(“%3d”,m);

    }

    }

    int plus(int k)

    {

    if(k==10)

    {

      exit(1);

      return 0;

    }

    else

    return(k);

    }

    OUTPUT:

    1 2 3 4 5 6 7 8 9

    Explanation:

    In the above example, in each iteration of the for loop the function plus() gets called. The function plus() checks the value of the formal argument ‘k’. If variable ‘k’ contains10, the program is terminated, otherwise the value of ‘k’ is returned as it is. Thus, the function plus() checks the value of the loop variable.

  2. Working with the while loop: Its syntax is shown in Table 10.9.

    Table 10.9  Function and while loop

    Without Function

    With Function

    while(condition)

    while(fun())

    {

    {

    }

    }

    This is a common syntax of the while loop statement.

    Where, fun() is a user-defined function.

     

    In the above example, in place of condition we are passing a function. The while checks the returned value of function.

    How it works with while statement? Below given is an example that illustrates the use of while statement.

       10.35  Write a program to call user-defined function through while loop.

     

    int main()

    {

    int x,y();

    clrscr();

    while(y()!=0)

    printf(“Value entered is non-zero”);

    return 0;

    }

    int y()

    {

    int x;

    printf(“\n Enter a Number :”);

    scanf(“%d”,&x);

    return(x);

    }

    OUTPUT:

    Enter a Number : 5

    Value entered is non-zero

    Enter a Number : 0

    Explanation:

    In the above example, y() is a user-defined function. The function is called through the while loop. When the control is passed to y() function, it reads a number through the terminal and returns it to the while loop. The while loop checks this value. If it is non-zero,the while loop executes and a message is displayed ‘value entered is non-zero’ otherwise if ‘0’ value is returned, the while loop terminates.

  3. Working with do–while loop. Its syntax is given in Table 10.10.

    Table 10.10  Function and do-while loop

    Without Function

    With Function

    do

    do

    {

    {

    }while(condition)

    }while(fun())

     

    Where, fun() is a user-defined function.

     This is a common syntax of the do-while loop statement.

    In the above example, in place of condition we are passing a function. The while checks the returned value of function.

       10.36  Write a program to call a user-defined function through do-while() loop.

     

    int main()

    {

    int x,y();

    clrscr();

    do

    printf(“Value enter is non-zero”);

    while(y()!=0);

    return 0;

    }

    int y()

    {

    int x;

    printf(“\n Enter a Number :”);

    scanf(“%d”,&x);

    return(x);

    }

    OUTPUT:

    Value enter is non-zero

    Enter a Number : 5

    Value enter is non-zero

    Enter a Number : 0

    Explanation:

    The above program is similar to the previous one. In the output, the message is displayed,though we have not entered any number. This is the only drawback of the do–while statement. It executes once, though the given condition is false.

10.12  FUNCTIONS WITH ARRAYS AND POINTERS
  1. Initialization of Array Using Function

    User initializes the array using statement like int d []={1,2,3,4,5}; instead of this, a function can also be directly called to initialize the array. The given below program illustrates this point.

       10.37  Write a program to initialize an array using functions.

     

    int main()

    {

    int k,c(),d[]={c(),c(),c(),c(),c()};

    clrscr();

    printf(“\n Array d[] elements are :”);

    for(k=0;k<5;k++)

    printf(“%2d”,d[k]);

    return(0);

    }

    int c()

    {

    static int m,n;

    m++;

    printf(“\nEnter Number d[%d] : ”,m);

    scanf(“%d”,&n);

    return(n);

    }

    OUTPUT:

    Enter Number d[1] : 4

    Enter Number d[2] : 5

    Enter Number d[3] : 6

    Enter Number d[4] : 7

    Enter Number d[5] : 8

    Array d[] elements are : 4 5 6 7 8

    Explanation:

    A function can be called in the declaration of an array. In the above program, d[] is an integer array and c() is a user-defined function. The function c() when called reads the value through the keyboard. The function c() is called from an array, i.e. the value returned by the function is assigned to the array.

  2. Passing Array Elements to Function

    Arrays are a collection of one or more elements of the same data type. Array elements can be passed to the function by value or reference. Below given programs explain both the ways.

       10.38  Write a program to pass the array element to the function. Use the call by value method.

     

    void main()

    {

    int k, show(int,int);

    int num[]={12,13,14,15,16,17,18};

    clrscr();

    for(k=0;k<7;k++)

    show(k,num[k]);

    }

    show(int m,int u)

    {

    printf(“\nnum[%d] = %d”,m+1,u);

    }

    OUTPUT:

    num[1]=12

    num[2]=13

    num[3]=14

    num[4]=15

    num[5]=16

    num[6]=17

    num[7]=18

    Explanation:

    The show() is a user-defined function. The array num[] is initialized with seven elements. Using for loop, the show() function is called for seven times and one element is sent per call. The function show() prints the element.

       10.39  Write a program to pass array element to the function. Use call by reference.

     

    void main()

    {

    void show(int*);

    int num[]={12,13,14,15,16,17,18};

    clrscr();

    show(num);

    }

    void show(int *u)

    {

      int m=0;

      printf(“\n num[7]={”);

      while(m!=7)

      {

        printf(“%2d,”,*(u++));

        m++;

      }

      printf(“\b }”);

    }

    OUTPUT:

    num[7]={12,13,14,15,16,17,18}

    Explanation:

    In the above program, base address of 0th element is passed to the function show(). The pointer *u contains base address of array num[]. The pointer notation prints the elements.

  3. Passing Reverse Array to Function

       10.40  Write a program to display array elements in the reverse order.

     

    void main()

    {

    int show(int*);

    int num[]={12,13,14,15,16,17,18};

    clrscr();

    show(&num[6]);

    }

    show(int *u)

    {

    int m=6;

    while(m!=−1)

    {

      printf(“\nnum[%d] = %d”,m,*u);

      u−−,m−−;

    }

    return(0);

    }

    OUTPUT:

    num[6]=18

    num[5]=17

    num[4]=16

    num[3]=15

    num[2]=14

    num[1]=13

    num[0]=12

    Explanation:

    Increment or decrement in any pointer points next or previous location of its type, respectively. In the above program, instead of the address of 0th element, the address of the last element is passed. The sixth element is the last element of the array. Decrement in pointer points to the address of the previous element of array.

  4. Copying Array

    We have already studied call by reference in which one can change the contents of any local variable of other function, provided its reference or address should be available. Using the call by reference method, copying contents of one array to another is possible.

       10.41  Write a program to copy array elements using user-defined function.

     

    void main()

    {

    int cpy(int*, int*),h;

    int a1[]={1,2,3,4,5},a2[5];

    clrscr();

    cpy(&a1[0],&a2[0]);

    printf(“Source Target”);

    for(h=0;h<5;h++)

    printf(“\n%5d\t\t%d”,a1[h],a2[h]);

    }

    int cpy(int *p,int *m)

    {

    int j=0;

    while(j!=5)

    {

      *m=*p;

      p++;

      m++;

      j++;

    }

    return(0);

    }

    OUTPUT:

    Source
    Target
    1
    1
    2
    2
    3
    3
    4
    4
    5
    5

    Explanation:

    The function cpy() collects the base addresses of both the arrays sent by the main() function. The pointer *p points to array a1[] and the pointer ‘*m’ points to array a2[]. ‘*m,elements of array a1[] are copied to arraya2[]. The for loop used in the main() function displays contents of both the arrays. Here, the function cpy() is called only once. Using the base addresses of the array the function ‘cpy()’ performs this task independently.

  5. Reading Private Array

       10.42  Write a program to read array of other function in main().

     

    void main()

    {

    int k;

    int arry();

    clrscr();

    for(k=0;k<5;k++)

    {

      printf(“\t%d”,arry());

    }

    }

    int arry()

    {

      static int k;

      int b[5]={1,2,3,4,5};

      return(b[k++]);

    }

    OUTPUT:

    1 2 3 4 5

    Explanation:

    In the above program, integer array b[] is declared and iniatlized in the function arry(). The function arry() is called five times. During each call, it returns successive elements of array b[] to function main(). Thus, all elements of array b[] are displayed.

  6. Interchange of Array Elements

       10.43  Write a program to interchange array elements of two array using functions.

     

    void main()

    {

    int read();

    void change(int*,int*);

    int x,a[5],b[5];

    clrscr();

    printf(“Enter 10 Numbers :”);

    for(x=0;x<10;x++)

    {

      if(x<5)

      a[x]=read();

      else

      b[x−5]=read();

    }

    printf(“\n Array A & B”);

    for(x=0;x<5;x++)

    {

      printf(“\n%7d%8d”, a[x],b[x]);

      change(&a[x],&b[x]);

    }

    printf(“\nNow A & B”);

    for(x=0;x<5;x++)

    {

      printf(“\n%7d%8d”, a[x],b[x]);

    }

    }

    int read()

    {

    int x;

    scanf(“%d”,&x);

    return(x);

    }

    void change(int *a, int *b)

    {

    int *k;

    *a=*a+*b;

    *b=*a−*b;

    *a=*a−*b;

    }

    OUTPUT:

    Enter 10 Numbers:

    1 2 3 4 5 6 7 8 9 0

    Array A & B

    1 6

    2 7

    3 8

    4 9

    5 0

    Now A & B

    6 1

    7 2

    8 3

    9 4

    0 5

    Explanation:

    Interchange of array elements can be done by call by reference. Here, we are passing address of array elements of arrays a[] and b[] to the function change(). The function change() interchanges the contents of the elements.

  7. Global Pointer

       10.44  Write a program to read array elements declared in different functions using global pointer declaration.

     

    int *p,*q;

    void main()

    {

    int m=0,call(int),k[5]={3,8,5,2,5};

    p=k;

    clrscr();

    call(5);

    while(m!=5)

    {

      printf(“%3d”,*q);

      m++;

      q++;

    }

    }

    int call(int j)

    {

    static int m=0,u[5]={5,1,6,0,6};

    q=u;

    while(m!=j)

    {

      printf(“%3d”,*p);

      m++;

      p++;

    }

    printf(“\n”);

    return(0);

    }

    OUTPUT:

    3 8 5 2 5

    5 1 6 0 6

    Explanation:

    In the above program, ‘p’ and ‘q’ are declared as global pointers, i.e. they are defined outside the main() function. The pointer ‘p’ contains the base address of array k[] and pointer ‘q’ contains base address of u[]. Hence, pointers ‘p’ and ‘q’ are global pointers. They can be accessed through any function.

10.13  PASSING ARRAY TO A FUNCTION

We can pass array as arguments to a function. Passing an array to a function with arguments means address of array is passed. Arrays for all the times are passed to function by address, i.e. array name is passed to the function. Example is illustrated as follows.

   10.45  Program to pass an array to function and compute the average of five floating point numbers.

 

#include <stdio.h>

#include <conio.h>

 

float avg( float [] );

void main()

{

  float array[5]={2.0,3.5,4.8,5.9,7.8};

  float average;

  clrscr();

  average= avg(array);

  printf(“\nAverage of five numbers is %f\n”, average );

  getch();

}

float avg( float a[5] )

{

  int i;

  float sum=0;

  for( i = 0; i < 5; ++i )

  sum=sum+a[i];

return (float)(sum/5);

}

OUTPUT:

Average of five numbers is 4.800000

Explanation:

Array is passed to the function avg(). One by one elements of an array are passed to the function avg() and addition of array element with a variable sum is performed. Finally, the average of five elements is returned to the calling function and answer is displayed.

   10.46  Program to pass an array to function and find the minimum value of the array using pointer.

 

#include <stdio.h>

#include <conio.h>

int min( int *);

void main()

{

  int array[5]={10,9,4,5,7},n;

  clrscr();

  printf(“Elements of array are:”);

  for(int i=0;i<5;i++)

  printf(“ %d”,array[i]);

  n= min(array);

  printf(“\nMinimum of five numbers is %d\n”, n );

  getch();

}

int min( int *a )

{

  int i;

  int min;

  min=*a;

  for( i = 1; i < 5; i++ )

  {

    if(min>*(a+i))

    {

      min=*(a+i);

    }

}

  return min;

}

OUTPUT:

Elements of array are: 10 9 4 5 7

Minimum of five numbers is 4

Explanation:

Here, in this program, min is a function called from the main program. Using call by reference the elements of an array are called in the function min(). Initially, it is assumed minimum value to the first element and compared with successive elements. In case, successive element is smaller than the element under comparison, swapping of elements is done. Eventually the element having minimum value is obtained and the same is displayed on the screen.

10.14  NESTED FUNCTIONS

A nested function refers to function within the function. The programmer can invoke function within a function. The following program gives an idea on how to define function within function.

   10.47  Write a program to display some messages in sub() and nest() functions.

 

#include<stdio.h>

#include<conio.h>

void main()

{

void sub();

clrscr();

printf(“\nWe are in main() function”);

sub();

printf(“\nWe are back in main() function”);

}

void sub()

{

void nest();

printf(“\nWe are in sub function”);

nest();

}

void nest()

{

printf(“\nWe are in nest function”);

}

OUTPUT:

We are in main() function

We are in sub function

We are in nest function

We are back in main() function

Explanation:

The function sub() is invoked from the main() and nest() from the sub() and messages are displayed. Prototypes for functions sub() and nest() are initialized at the start of functions.

   10.48  Write a program to invoke sub() and nest() functions and perform some arithmetic operations.

 

#include<stdio.h>

#include<conio.h>

void main()

{

void sqr();

float a=5.5;

clrscr();

printf(“\nIn main() %g”,a);

sqr();

printf(“\n Back in main() %g”,a*a);

}

void sqr()

{

void cube();

float b=2.1;

printf(“\n In sub() %g”,b*b);

cube();

}

void cube()

{

float b=1.1;

printf(“\n In nest%g”,b*b*b);

}

OUTPUT:

In main() 5.5

In sub 4.41

In nest 1.331

Back in main() 30.25

Explanation:

Invocation of functions is the same as done in the previous program, and only some operations are performed and results are displayed.

10.15  RECURSION

So far, we have seen function calling one another. In programming, there might be a situation where a function needs to invoke itself. The C language supports recursive feature, i.e. a function is called repetitively by itself. The recursion can be used directly or indirectly. The direct recursion function calls to itself till the condition is true. In indirect recursion, a function calls to another function and then called function calls to the calling function.

When a function calls itself until the last call is invoked till that time the first call also remains open. At every time, a function invoked, the function returns the result of previous call. The sequence of return ensues all the way up the line until the first call returns the result to caller function.

   10.49  Write a program to call the main() function recursively and perform the sum of one to five numbers.

 

int x,s;

void main(int);

void main(x)

{

s=s+x;

printf(“\n x = %d s = %d”,x,s);

if(x==5)

exit(0);

main(++x);

}

OUTPUT:

x = 1 s = 1

x = 2 s = 3

x = 3 s = 6

x = 4 s = 10

x = 5 s = 15

Explanation:

In the above program, variables x and y are declared outside the main() function. Initially, their values are zeros. Followed by it, the prototype of function main() is defined. The variable x is passed through the main() function. The variable x is added to variable still the value of x reaches 5. Every time the function main() is called repeatedly and x is incremented. The result of the program is displayed at the output. The value of x in main() is 1because it is a command line argument.

The recursive function main() is called as in Table 10.11. The analysis of each step is given for understanding.

Table 10.11  Steps of the recursive function

Function Call

Value of x

Value of s (sum)

main(1)

x = 1

s=1 ( 0 + 1 ) = 1

main(2)

x = 2

s=3 ( 2 + 1 + 0 ) = 3

main(3)

x = 3

s=6 ( 3 + 2 + 1 + 0 ) = 6

main(4)

x = 4

s=10 ( 4 + 3 + 2 + 1 + 0 ) = 10

main(5)

x = 5

s=15 ( 5 + 4 + 3 + 2 + 1 + 0 ) = 15

   10.50  Write a program to calculate triangular number of an entered number through the keyboard using recursion.

 

void main()

{

int n,t,tri_num(int);

clrscr();

printf(“\n Enter a Number :”);

scanf(“%d”,&n);

t=tri_num(n);

printf(“\n Triangular number of %d is %d”,n,t);

}

int tri_num(int m)

{

int f=0;

if(m==0)

return(f);

else

f=f+m+tri_num(m−1);

return(f);

}

OUTPUT:

Enter a Number : 5

Triangular Number of 5 is 15

Explanation:

In the above program, a number is entered whose triangular number is to be calculated. The number is passed to the function tri_num(). The value of variable n is copied to variable m. In the tri_num() function, the entered number is added to variable f. The entered number is decremented and the tri_num function is called repetitively (recursively) till the entered number becomes zero.

   10.51  Write a program using recursion to display sum of digits of a given number.

 

# include <stdio.h>

# include <conio.h>

int sum(int);

void main ()

{

int num,f;

clrscr();

printf (“\n Enter a number : “);

scanf (“%d”, &num);

f=sum(num);

printf (“\n Sum of the all digits of given number (%d) is (%d)”,num,f);

getch();

}

int sum(int f)

{

if(f==0)

  return f;

  else

  return (f%10)+sum(f/10);

}

OUTPUT:

Enter a number: 654

Sum of all the digits of the given number (654) is (15)

10.16  TYPES OF RECURSION

Recursion process is a little bit difficult, but if one keeps track of the sequence in which statements are executed then it is easy to understand. Recursion is one of the most dominant tools used in the programming technique. There are various situations when we need to execute a block of statements for a number of times depending on the condition at the time recursion is useful. Recursion is used to solve a problem, which have iterations in the reverse order. Data structures also support recursion, for example tree supports recursion. Various programs are solved with recursion. The major application of recursion is game programming where a series of steps can be solved with recursion.

When a function calls itself it is called recursion. Recursions are of two types:

  1. Direct recursion
  2. Indirect recursion.

When a function calls itself, this type of recursion is direct recursion. In this type, only one function is involved. In indirect recursions, two function calls each other. Figure 10.2 describes direct and indirect recursions.

Figure 10.2  Types of recursion

The recursion is one of the applications of stack. Stacks are also explained in this book. There are several problems without recursion; their solution is lengthy. The programming languages like c, c++allow us to define the user-defined function. Functions in the programming languages are very useful because by using a function a separate block of statements can be defined. This block can be invoked a number of times anywhere in the program.

Two essential conditions should be satisfied by a recursive function. First every time a function calls itself directly or indirectly, the function should have a condition to stop the recursion. Otherwise, an infinite loop is generated that will halt the system. Some people think that recursion is a very needless luxury in the programming language. Using iteration, one can solve the problems. However, in programming at some situation, there is no substitute for recursion.

There are some kinds of problems associated with recursive functions that are not present in the non-recursive function. A function itself or any other function can invoke the recursive function. To ensure execution, it is very essential for the function to save the return address in order to return at a proper location. Also the function has to save the formal and local variables.

   10.52  Write a C program to calculate factorial of a given number using recursion.

 

int fact(int);

void main()

{

int num,f;

clrscr();

printf(“\n Enter a number :”);

scanf(“%d”,&num);

f=fact(num);

printf(“\n Factorial of (%d) is (%d)”,num,f);

}

int fact(int f)

{

if(f==1) return f;

else return f*fact(f−1);

}

OUTPUT:

Enter a number: 4

Factorial of (4) is (24)

Explanation:

In the above program, fact() is a recursive function. The entered number is passed to function fact(). When function fact() is executed, it is repeatedly invoked by itself. Every time a function is invoked, the value of f is reduced by one and multiplication is carried out. The recursive function produces the numbers 4, 3, 2 and 1. The multiplication of these numbers is taken out and it return to main() function.

10.17  RULES FOR RECURSIVE FUNCTION
  1. In recursion, it is essential to call a function itself, otherwise recursion would not take place.
  2. Only the user-defined function can be involved in the recursion. Library function cannot be involved in recursion because their source code cannot be viewed.
  3. A recursive function can be invoked by itself or by other function. It saves return address with the intention to return at proper location when return to a calling statement is made. The last-in-first-out nature of recursion indicates that stack data structure can be used to implement it.
  4. Recursion is turning out to be increasingly important in non-numeric applications and symbolic manipulations.
  5. To stop the recursive function, it is necessary to base the recursion on test condition, and proper terminating statement such as exit() or return must be written using the if()statement (see Figure 10.3).

    Figure 10.3  Terminating statement in recursion

  6. The user-defined function main() can be invoked recursively. To implement such recursion, it is necessary to mention prototype of function main(). An example in this regard is as follows.

   10.53  Write a program to call main() recursively.

 

# include <process.h>

char str[]=“Have a Good Day”;

int x=0;

void main(void);

void main()

{

switch(str[x])

{

  case ‘H’ :

  clrscr();

  default:

  printf(“%c”,str[x]);

  break;

  case ‘\0’:

  exit(0);

  break;

}

x++;

main();

}

OUTPUT:

Have a Good Day

Explanation:

In this program, main() program is invoked recursively. A prototype of function main() is given before the function definition. In recursion, the function invoked should have return type and arguments. Working of recursion is briefed as follows.

  1. When a recursive function is executed, the recursion calls are not implemented instantly. All the recursive calls are pushed on to the stack until the terminating condition is not detected. As soon as the terminating condition is detected, the recursive calls stored in the stack are popped and executed. The last call is executed first, then the second, third and so on.
  2. During recursion, at each recursive call new memory is allocated to all the local variables of the recursive functions with the same name.
  3. At each call, the new memory is allocated to all the local variables; their previous values are pushed onto the stack and with its call. All these values can be available to the corresponding function call when it is popped from the stack.
10.18  DIRECT RECURSION

In this type, only one function is involved which calls itself until the given condition is true. The reader can refer to program numbers 10.45 and 10.46. Following programming example is given on Direct recursion.

10.54  Write a program to calculate triangular number using recursion.

 

# include <process.h>

void main()

{

int trinum(int);

int t,x;

clrscr();

printf(“\n Enter a Number :”);

scanf(“%d”,&x);

t=trinum(x);

printf(“\n Triangular Number of %d is %d”,x,t);

}

int trinum(int x)

{

int f=0;

if(x==0) return f;

else f=f+x+trinum(x-1);

return f;

}

OUTPUT:

Enter a Number: 4

Triangular Number of 4 is 10

Explanation:

In the above program, a function trinum() is defined which calls itself. An integer is entered through the keyboard and it is stored in the variable x. In function trinum(), the function calls itself and decreases the value of x passed by one. The return values are added to variable f. When the value of x becomes zero, the recursive process ends and the total sum is returned to variable t in function main(). The value of t is triangular of number means that the sum of all the numbers between 1 to entered number. The recursive function is called repetitively by itself without completing the execution of previous call. When program ends and the control about to return to caller function the return statement is executed for number of times equal to the function is called recursively. With F7 key, one can keep the track of number of times execution of function.

When a function returns, three actions are done. The return address is placed in the safe location. The data stored in local variables of function is freed. The previously saved address is retrieved. The return value of function is returned and put in the safe location and calling program receives it. Normally, the location is a hardware register, which is placed in CPU for the same purpose.

Figure 10.4  Functions calling one another

As shown in Figure 10.4, the main function invoke the function B. The function B invokes the function C and again C invokes D. The figure shows the control is present in function D. In every function,a location is reserved for storage of return address. The return address location of function D contains the address of statement in C immediately after the function invocation statement.

Every time a recursive function invokes itself, new data variables are created and memory is allocated. The data area contains all local variables and return addresses. In the recursion of function,the data area is not connected only with the function but closely associated with the particular function call. In every call new data area is allocated. While returning to the calling function the data area is de-allocated or freed and the former data area turns into current.

The recursion in C and C++ language is more expensive as compared to non-recursive function.It not only takes more space but is also time consuming. In some system programs such as compiler,operating system if a program contains recursive function, it will be executed for a lot of times. In such a case, an alternate non-recursive function may be defined.

10.19  INDIRECT RECURSION

In this type of recursion, two or more functions are involved in the recursion. The indirect recursion does not make any overhead as direct recursion. When control exits from one function and enter into another function, the local variables of former function are destroyed. Hence, memory is not engaged.The following program explains the indirect recursion.

10.55  Write a program to demonstrate recursion between two functions.

 

int s=0;

void show(void);

void main()

{

if(s==5) exit(0);

show ();

}

void show()

{

printf(“ %d”,s);

s++;

main();

}

OUTPUT:

0  1  2  3  4

Explanation:

In the above program, two user-defined functions are defined as main() and show(). The s is a global variable. The main() function invokes the show() function and the show()function invokes the main() function. The value of s is increased and displayed. When the value of s reaches to 5, the program is terminated.

10.56  Write a program to display numbers in different rows.

 

int s;

void show(void);

void main()

{

if(s==0) clrscr();

if(s==10) exit(0);

show();

}

void show()

{

int j;

for(j=0;j<=s;j++)

printf(“ %d”,j);

printf(“\n);

s++;

main();

}

OUTPUT:

0

0 1

0 1 2

0 1 2 3

0 1 2 3 4

0 1 2 3 4 5

0 1 2 3 4 5 6

0 1 2 3 4 5 6 7

0 1 2 3 4 5 6 7 8

0 1 2 3 4 5 6 7 8 9

Explanation:

This program is the same as the last one. Here, depending on the value of variable s the iteration of the for loop is performed.

10.20  RECURSION VERSUS ITERATIONS

Recursion and iteration are based on the control structure. Iteration uses repetition structure where as recursion uses selection structure. Both recursion and iteration repeat the process but with a few differences. Let us discuss the differences.

In iteration repetition structure is explicitly used whereas in recursion the same function is invoked by itself. Both recursion and iteration go through the termination test. Iteration terminates when the loop continuation condition fails. The recursion also terminates when the test for termination is satisfied.Both iteration and recursion can be executed infinitely. When recursion and iteration are defined without termination condition, they turn to infinite loop. Recursion has several overheads. Each time a function is executed, a new copy of function is created. Memory is occupied by the functions. In iteration, only once the variable is created. Thus, iteration is very useful and efficient as compared to recursion. However,there are a few problems that cannot be solved with iteration, and recursion perfectly works.

We have studied both recursion and iteration. They can be applied depending upon the situation.

Table 10.12 explains the differences between recursion and iteration.

Iterative process is given in Figure 10.5.

Table 10.12  Recursion versus iterations

Recursion

Iteration

Recursion is the term given to the mechanism of defining a set or procedure in terms of itself.

The block of statement is executed repeatedly using loops.

A conditional statement is required in the body of the function for stopping the function execution.

The iteration control statements itself contain statements for stopping the iteration. At every execution,the condition is checked.

At some places, the use of recursion generates extra overhead. Hence, it is better to skip when easy solution is available with iteration.

All problems cannot be solved with iteration.

Recursion is expensive in terms of speed and memory.

Iteration does not create any overhead.All the programming languages support iteration.

Figure 10.5   Iterative processes

Initialization:The variables involved in iteration process are initialized. These variables are used to decide when to end the loop.

Decision: The decision variable is used to decide if to continue or discontinue the loop. When the condition is satisfied, control goes to return, else goes to computation block.

Computation: The required processing or computation is carried out in this block.

Update: The decision argument is changed and shifted to the next iteration.

The common algorithm for any kind of recursive function is as per Figure 10.6.

 

Figure 10.6  Recursive process

Preliminary Part: The use of this block is to store the local variables, formal arguments and return address. The end-part will restore these data. Only recently saved arguments, local variables and return address are restored. The variables last saved are restored first.

Body: If the test condition is satisfied, it performs complete processing and control passes to end-block. If not partial processing is performed and a recursive call is made. The body also contains call to itself. There may be one or more calls. Every time a recursive call is made, the preliminary part of the function saves all the data. The body also contains two processing boxes, i.e. partial processing and complete processing. In some programs, the result can be calculated by only complete processing.For this, the recursive call may not be required. For example, we want to calculate factorial of one. The factorial of one is one. For this, it is needless to call function recursively. It can be solved by transferring control to complete processing box.

In other case, if five is given for factorial calculation, the factorial of five cannot be calculated in one step. Hence, the function will be called recursively. Everytime one step is solved, i.e. 5*4*3 and so on. Hence, it is called partial processing.

Depth of Recursion: The recursion function calls itself infinite times. If we want to calculate factorial of five, then we can easily estimate the number of times the function would be called. In this case, we can determine the depth of the recursive function. In complex programs, it is difficult to determine the number of calls of recursive function.

10.21  THE TOWERS OF HANOI

The Tower of Hanoi has historical roots in the ceremony of the ancient tower of Brahma. There are n disks of decreasing sizes mounted on one needle as shown in the Figure 10.7 (a).Two more needles are also required to stack the entire disk in the decreasing order. The use of third needle is for impermanent storage. While mounding the disk, following rules should be followed.

  1. At a time only one disk may be moved.
  2. The disk may be moved from any needle to another needle.
  3. No larger disk should be placed on top of the smaller disk.

Our aim is to move the disks from A to C using the needle B as an intermediate by obeying the above three conditions. Only top-most disks can be moved to another needle. The following figures and explanation clear the process of Tower of Hanoi stepwise.

In Figure 10.7 (a), the three needles are displayed in the initial state. The needle X contains three disks and there are no disks on needle Y and Z.

Figure 10.7(a)   Towers of Hanoi

In Figure 10.7 (b), the top-most disk is moved from needle X to Z. The arrow indicates the movement of disk from one needle to another needle.

Figure 10.7 (b)  Towers of Hanoi

In Figure 10.7 (c), the disk from the X needle moves to the Y needle.

Figure 10.7 (c)   Towers of Hanoi

In Figure 10.7 (d), the disk from Z needle moves to Y needle. Needle Y has two disks.

Figure 10.7 (d)   Towers of Hanoi

In Figure 10.7 (e), the disk from the X needle moves to the Z needle. Now there is no disk in the X needle.

Figure 10.7 (e)   Towers of Hanoi

In Figure 10.7 (f ), the disk from the Y needle moves to the X needle.

Figure 10.7 (f)   Towers of Hanoi

In Figure 10.7 (g ), the disk from the Y needle moves to the Z needle. The Y needle contains no disk.

Figure 10.7 (g)   Towers of Hanoi

In Figure 10.7 (h ), the disk from the X needle moves to the Z needle. Thus, the Z needle contains all the three disks of the X needle shown in Figure 10.7 (a). Thus, the problem is solved.

Figure 10.7 (h)   Towers of Hanoi

The above process is summarized as follows:

  1. The three needles are displayed in the initial state.
  2. The needle X contains three disks and there are no disks on needle Y and Z.
  3. The top-most disk is moved from the needle X to Z
  4. The disk from the X needle moves to the Y needle.
  5. The disk from the Z needle moves to the Y needle.
  6. The disk from the X needle moves to the Z needle.
  7. The disk from the Y needle moves to the X needle.
  8. The disk from the Y needle moves to the Z needle.
  9. The disk from the X needle moves to the Z needle.

10.57  Write a program to illustrate the towers of Hanoi.

 

void hanoi(int,char,char,char);

void main()

{

int num;

printf(“\n Enter a Number :”);

scanf(“%d”,&num );

clrscr();

hanoi(num,’A’,’C’,’B’);

}

void hanoi(int num, char f_peg,char t_peg, char a_peg)

{

  if(num==1)

  {

  printf(“\nmove disk 1 from Needle %c to %c”,f_peg,t_peg);

  return;

}

hanoi(num-1,f_peg,a_peg,t_peg);

printf(“\nmove disk %d from Needle %c to Needle %c”,num,f_peg, t_peg);

hanoi(num-1,a_peg,t_peg,f_peg);

}

OUTPUT:

Enter a Number: 3

move disk 1 from Needle A to C

move disk 2 from Needle A to Needle B

move disk 1 from Needle C to B

move disk 3 from Needle A to Needle C

move disk 1 from Needle B to A

move disk 2 from Needle B to Needle C

move disk 1 from Needle A to C

Explanation:

In the above program, numbers of disks are entered. The function Hanoi() is invoked from main(). The A, B and C are needles. If value of n is one, and the disk is transferred from A to C and program ends. If the value of n is greater than one, then the Hanoi() function invokes itself recursively. Every time the value of n is decreased by one. The output of the program is shown as above.

10.22  ADVANTAGES AND DISADVANTAGES OF RECURSION

Advantages

  1. Although, at most of the times, a problem can be solved without recursion, but in some situations in programming, it is a must to use recursion. For example, a program to display a list of all files of the system cannot be solved without recursion.
  2. The recursion is very flexible in data structure like stacks, queues, linked list and quick sort.
  3. Using recursion, the length of the program can be reduced.

Disadvantages

  1. It requires extra storage space. The recursive calls and automatic variables are stored on the stack. For every recursive calls, separate memory is allocated to automatic variables with the same name.
  2. If the programmer forgets to specify the exit condition in the recursive function, the program will execute out of memory. In such a situation user has to press Ctrl+ break to pause and stop the function.
  3. The recursion function is not efficient in execution speed and time.
  4. If possible, try to solve a problem with iteration instead of recursion.
10.23  EFFICIENCY OF RECURSION

We have studied both advantages and disadvantages of recursion. We also studied iteration as an alternative to recursion. The major overhead of recursion is the memory it occupies and execution time.A non-recursive function will require minimum memory and less time for execution as compared to the recursive function. The recursive function uses stack to push and pop the local variables. In non-recursive function, the above push and pop operations with stack can be skipped. However, at some situation in programming, the use of recursion is a must. If the part of program is to be invoked frequently, in such a case it is better to develop a non-recursive function.

10.58  Write a program to display the given string 10 times using recursive call of function.

 

# include <process.h>

char str[]=“Have a Good Day”;

int x=1;

void main(void);

void main()

{

 printf(“\n %.2d] %s”,x,str);

 x++;

 switch(x)

 {

  case 1:

  clrscr();

  default :

  main();

  case 11:

  exit(1);

 }

}

OUTPUT:

01] Have a Good Day

02] Have a Good Day

03] Have a Good Day

04] Have a Good Day

05] Have a Good Day

06] Have a Good Day

07] Have a Good Day

08] Have a Good Day

09] Have a Good Day

10] Have a Good Day

Explanation:

The logic of the program is the same as in the previous one. In this program, the entire string is displayed at each call and x is incremented. The main() is called through the switch case structure. When x reaches 11, the program gets terminated.

10.24  LIBRARY FUNCTIONS

Table 10.13   Library function

S.No.
Function
Description

1

sqrt(j)

Calculates square root of j

2

log(j)

Natural logarithm of j base e

3

ceil(j)

Rounds j to the smallest integer !< j

4

pow(j,k)

j raised to power k

5

rand()

Generates random number

10.59  Write a program to demonstrate the use of functions given in Table 10.13.

 

# include <math.h>

void main()

{

clrscr();

printf(“\n Square root of 9 is %g”,sqrt(9));

printf(“\n log of 5 is : %g”,log(5));

printf(“\n 10.3 after ceil () : %g”,ceil(10.3));

printf(“\n power 3 raised to 4 is : %g”,pow(3,4));

}

OUTPUT:

Square root of 9 is 3

log of 5 is : 1.60944

10.3 after ceil() : 11

power 3 raised to 4 is : 81

Explanation:

In the above program, the sqrt() function returns the square root of 9. Log() gives result 1.60944. The ceil() promotes 10.3 to 11 and pow() calculates 34. All the above functions are defined in math.h header file.

10.60  Write a program to demonstrate the use of rand() function

 

# include <stdlib.h>

void main ()

{

int j;

clrscr();

for(j=0;j<=15;j++)

{

printf(“%10d”,1+(rand()%6));

if(j%5==0)

printf(“\n”);

}

}

OUTPUT :

5

5  3  5  5  2

4  2  5  5  5

3  2  2  1  5

Explanation:

In the above program, the rand() function produces random number which modular divided and added 1. The obtained number is displayed. The last printf() inserts a line.

SUMMARY

This chapter is focused on functions. You have studied how to initialize and use functions while writing programs in C. How the functions are interacted with one another is also explained with examples.It is also described how to use function as argument. The reader should know that the function always returns an integer value. Executing programs as illustrated in this chapter can be followed. Besides non-integer specifying data type in function prototype can also return a value. The recursive nature of function is also explained with suitable examples. Direct and indirect recursive functions have been explained with programming examples.

EXERCISES

I  True or false:

  1. Every C Program starts with function main().
  2. Library function can be defined by the user.
  3. User-defined functions have serious limitations.
  4. The sum() is a standard library function.
  5. The abs() is a standard library function.
  6. The abs() gives absolute value.
  7. Mathematical library functions are defined in math.h.
  8. Function not returning any value is known as avoid.
  9. The return() statement can return more than one value at a time.
  10. The arguments of a function which are invoked are called actual arguments.
  11. A user-defined function cannot call another user-defined function.
  12. A user-defined function cannot call the main() function.
  13. The scope of local variables is limited to the block in which they are defined.
  14. Actual and formal arguments can have the same variable type.
  15. In the call by value, values are passed to formal arguments.
  16. In call by address, formal arguments are pointer to actual arguments.
  17. A change made in formal arguments can change the value of variable permanently.
  18. A function prototype gives information in advance to the compiler.
  19. A function can pass arguments to another function.
  20. The data type before the function name indicates the type of value the function will return.
  21. By default function returns integer value.
  22. When a function calls itself the process is called recursion.
  23. Like variable, functions also have address in the memory.
  24. Functions can be invoked using pointers to function.
  25. Function prototype is not necessary to match with actual function definition.

II   Match the following correct pairs given in Group A with Group B:

  1.  

  2.  

  3.  

III   Select the appropriate option from the multiple choices given below:

  1. Arrays are passed as arguments to a function by
    1. value
    2. reference
    3. Both (a) and (b)
    4. None of the above
  2. Following one keyword is used for function not returning any value
    1. void
    2. int
    3. auto
    4. None of the above
  3. Recursion is a process in which a function calls
    1. itself
    2. another function
    3. main() function
    4. None of the above
  4. By default the function returns
    1. integer value
    2. float value
    3. char value
    4. None of the above
  5. The meaning of keyword void before function name means
    1. function should not return any value
    2. function should return any value
    3. no arguments are passed
    4. None of the above
  6. The function name itself is
    1. an address
    2. value
    3. definition
    4. None of the above
  7. A global pointer can access variable of
    1. all user-defined functions
    2. only main() function
    3. only library functions
    4. None of the above
  8. What will be the values of x and s on execution?

    int x,s;

    void main(int);

    void main(x)

    {

    printf(“\n x = %d s = %d”,x,s);

    }

    1. x=1 s=0
    2. x=0 s=0
    3. x=1 s=1
    4. None of the above
  9. The main()is a
    1. user-defined function
    2. library function
    3. keyword
    4. None of the above
  10. What will be the value of x after execution

    void main()

    {

    float x=2.2,sqr(float),y;

    y=(int)sqr(x);

    printf(“\n x=%g”,y);

    }

    float sqr(float m)

    {

    return (m*m);

    }

    1. x=4
    2. x=4.84
    3. x=4.50
    4. None of the above
  11. What is the data type of variable m

    void main()

    {

    int sqr(int);

    int x=2;

    int sqr(x);

    }

    sqr(m)

    {

    return (m*m);

    }

    1. int
    2. float
    3. char
    4. void

IV  Attempt the following programming exercises:

  1. Write a program to display three different Metro names of India by using different functions.
  2. Write a program with two functions and call one function from other.
  3. Write a program which takes an int argument and calculates its cube.
  4. Write a program to display the table of given number. Write different functions for accepting the input, calculating the table and displaying the value.
  5. Write a program to calculate the sum of digits of a number. Use a function to return the sum.
  6. Write a program to swap the two variables present in one function to other function.
  7. Write a program to sort an array (in descending order) in different function and return it to the original function.
  8. Write a program to display ‘Hello!’five times.Create a user-defined function message().
  9. Write a program to calculate average marks of five subjects by using pass by value.
  10. Write a user-defined function for performing the following tasks.
    1. Cube of a number
    2. Perimeter of a circle
    3. Conversion of binary to decimal
    4. Addition of individual digits of a given number
  11. Write a program to reverse the given number recursively.
  12. Write a program to add 1 to10 numbers recursively.

V   What will be the output/s of the following program/s?

  1.  

    void main()

    {

    clrscr();

    printf(“\n India is”);

    sub();

    getche();

    }

    sub()

    {

    printf(“my Country”);

    }

  2.  

    void main()

    {

    clrscr();

    printf(“\n India is”);

    sub();

    secondsub();

    printf(“\n I love my country”);

    getche();

    }

    sub()

    {

    printf(“my Country”);

    }

    secondsub()

    {

    printf( “ ”);

    }

  3.  

    void main()

    {

    clrscr();

    sum();

    getche();

    }

    sum()

    {

    int a=7,f=0,d;

    while(a>=1)

    {

      f=f+a;

      a=a-1;

    }

    printf(“\n%d”,f);

    }

  4.  

    void main()

    {

    clrscr();

    fact();

    getche();

    }

    fact()

    {

    int a=5,f=1,d;

    while(a>=1)

    {

      f=f*a;

      a=a-1;

    }

    printf(“\n%d”,f);

    }

  5.  

    void main()

    {

    int a=4,fac;

    clrscr();

    fac=fact(a);

    printf(“\n%d”,fac);

    getche();

    }

    int fact(int x)

    {

    int f=1,d;

    while(x>=1)

    {

      f=f*x;

      x=x-1;

    }

    return(f);

    }

  6.  

    void main()

    {

    int a=3,b=4,c=5,d;

    clrscr();

    mul();

    d=a+b+c;

    printf(“\n%d”,d);

    getche();

    }

    void mul()

    {

    int a=2,b=3,c=4,d;

    d=a*b*c;

    printf(“\n%d”,d);

    }

  7.  

    void main()

    {

    int result;

    clrscr();

    result=sq();

    printf(“\n Result of function

    is= %.2d”,result);

    getche();

    }

    int sq()

    {

    int x=2,y=3;

    return(x*x+y*y);

    }

  8.  

    void main()

    {

    int num=5,result;

    clrscr();

    result=cb(num);

    printf(“\n Result of function is= %.2d”,result);

    getche();

    }

    int cb(int x)

    {

    float y;

    y=x*x*x;

    return(y);

    }

VI  Find the bug/s in the following program/s?

  1.  

    void main()

    {

    sum(int f);

    int f=2;

    clrscr();

    void sum(f);

    }

    sum(int j)

    {

    printf(“%d”,j);

    }

  2.  

    void main()

    {

    int a=0, B();

    a=a+ +-B();

    printf(“%d”,a);

    }

    int B()

    {

    int x;

    printf(“Enter a Number”);

    scanf(“%d”,&x);

    return x;

    }

  3.  

    void main()

    {

    int sum(int j, k,l);

    clrscr();

    sum(1,2,3);

    }

    sum(int j,int k, int l)

    {

    printf(“%d %d %d”,j,k,l);

    }

  4.  

    void main()

    {

    void show (void);

    clrscr();

    show();

    }

    void show()

    {

    puts(“Hello”);

    }

  5.  

    void main()

    {

    float ave(int,int,int);

    float av;

    clrscr();

    av=ave (2,3,5);

    printf(“%g”,av);

    }

    float ave(int j,int k, int l)

    {

    float x= j+k+l/3.0;

    }

  6.  

    void A()

    {

    clrscr();

    printf(“\n in A”);

    }

    void main()

    {

    A(‘x’,’x’);

    }

  7.  

    void main()

    {

    int B();

    B(5.5);

    }

    B(float a)

    {

    clrscr();

    printf(“ %f”,a);

    }

  8.  

    void main()

    {

    int B();

    B();

    }

    C()

    {

    printf(“In C”);

    }

    B()

    {

    printf(“In B”);

    C();

    B();

    }

VII   Answer the following questions:

  1. Write the definition of a function Mention the types of functions available in C.
  2. How do functions help to reduce the program size?
  3. Differentiate between library and user-defined functions.
  4. How does a function works? Explain how arguments are passed and results are returned?
  5. List any five library functions and illustrate them with suitable examples.
  6. What are actual and formal arguments?
  7. What are the uses of the return() statements?
  8. What does it mean if there is no return statement in the function?
  9. What are the void functions?
  10. Why is it possible to use the same variable names for actual and formal arguments?
  11. What is the main()function in C? Why is it necessary in each program?
  12. Explain the different formats of return() statements.How many values return statement returns at each call?
  13. What is a global pointer? Illustrate with a suitable example.
  14. Why the return statement is not necessary when function is called by reference?
  15. Distinguish between function prototype and function definition.
  16. Does the function prototype match with the function definition?
  17. Can we define a user-defined function with the same library function name?
  18. What is recursion? Explain its advantages.
  19. Explain the types of recursions.
  20. Is it possible to call library function recursively?
ANSWERS

I  True or false:

Q.
Ans.

1.

T

2.

F

3.

F

4.

F

5.

T

6.

T

7.

T

8.

T

9.

F

10.

F

11.

F

12.

F

13.

T

14.

T

15.

T

16.

T

17.

F

18.

T

19.

T

20.

T

21.

T

22.

T

23.

T

24.

T

25.

F

II  Match the following correct pairs given in Group A with Group B:

  1. Q.
    Ans.

    1.

    D

    2.

    C

    3.

    A

    4.

    B
  2. Q.
    Ans.

    1.

    C

    2.

    C

    3.

    B

    4.

    A
  3. Q.
    Ans.

    1.

    B

    2.

    C

    3.

    D

    4.

    A

III  Select the appropriate option from the multiple choices given below:

Q.
Ans.

1.

c

2.

a

3.

a

4.

a

5.

a

6.

c

7.

a

8.

a

9.

a

10.

a

11.

a

V   What will be the output/s of the following program/s?

Q.
Ans.

1.

India is my Country

2.

India is my Country

I love my country

3.

28

4.

120

5.

24

6.

24 12

7.

Result of function is= 13

8.

Result of function is= 125

VI  Find the bug/s in the following program/s?

Q.
Ans.

1.

int sum (int) is needed instead of sum(int f) .

2.

Prototype of function sum() is incorrect, but program runs.

3.

Function prototype error.

4.

In Function definition void is not mentioned.

5.

Return statement is not mentioned.

6.

No Bug.

7.

Function prototype error.

8.

infinite recursion.