49
CHAPTER -5 FUNCTIONS Contents : 5.0 Introduction 5.0.1 What is a function? 5.0.2 Library functions 5.0.3 User-defined functions 5.1 Objectives 5.2 Function Definition 5.3 Calling a Function 5.3.1 Calling function with no return value 5.3.2 Calling function with a return value 5.3.3 Calling a function with arguments 5.4 Function Prototypes 5.5 Categories of Functions 5.5.1 Functions with arguments and return value 5.5.2 Functions with arguments and no return value 5.5.3 Functions with no arguments and return value 5.5.4 Functions with no arguments and no return value 5.6 Built-In Functions 5.7 Recursive Functions 5.7.1 What is recursion? 5.7.2 How to write a recursive function 5.8 Storage Classes 5.8.1 Global & Local Variables 5.8.2 Storage Classes 5.8.2.1 Automatic variables 5.8.2.2 External variables 5.8.2.3 Static variables 5.8.2.4 Register variables 5.9 Summary 5.10 Review questions 5.11 Programming Exercises

c.p function

Embed Size (px)

DESCRIPTION

concept of functions

Citation preview

Page 1: c.p function

CHAPTER -5FUNCTIONS

Contents:

5.0 Introduction5.0.1 What is a function?5.0.2 Library functions5.0.3 User-defined functions

5.1 Objectives

5.2 Function Definition

5.3 Calling a Function5.3.1 Calling function with no return value 5.3.2 Calling function with a return value

5.3.3 Calling a function with arguments

5.4 Function Prototypes

5.5 Categories of Functions5.5.1 Functions with arguments and return value5.5.2 Functions with arguments and no return value5.5.3 Functions with no arguments and return value5.5.4 Functions with no arguments and no return value

5.6 Built-In Functions

5.7 Recursive Functions5.7.1 What is recursion?5.7.2 How to write a recursive function

5.8 Storage Classes5.8.1 Global & Local Variables5.8.2 Storage Classes

5.8.2.1 Automatic variables5.8.2.2 External variables5.8.2.3 Static variables

5.8.2.4 Register variables

5.9 Summary

5.10 Review questions

5.11 Programming Exercises

Page 2: c.p function

5.0 Introduction

5.0.1 What is a function?

Consider the following program to calculate area of a circle

void main (){

float r, area;printf(“\nEnter radius of circle:”);scanf(“%f”,&r);area=3.14159*r*r;printf(“\narea=%f”,area);

}

The above example is one of the functions which contain its own set of statements for the task to find area of a circle. Now we can understand what is a function

A function is self contained program segment which performs a specific task. For example

A function to find area of a circle A function to find factorial of a number A function to find gcd of two numbers

Here the task of each example is different and writing the set of statements is also independent to each other.

Generally a C program consists of one or more modules called functions, one of these functions must be called main. Execution of the program will always begin by carrying out the instructions in main. Other functions are subordinate to main and perhaps to one another.

Example5.1: Program to read a negative number and find square root of its absolute value

void main (){

int a, b , c ;printf(“ \n enter a negative number : ”);scanf(“%d”, &a ); b = abs( a );d = sqrt( b );printf( “ \n a=%d b=%d c=%d ”, a, b, c );

}

In this program the different functions are main() is the main function of the program printf(), scanf(), abs() and sqrt() are the functions that are called by main( )

C functions can be classified as

Library functions (Built-in functions) User-defined functions

Page 3: c.p function

5.0.2 Library functions

Which are already predefined in the system and stored in C Library files. The meaning and purpose of these functions are fixed. It is not possible to change its meaning and purpose by the user, but user can utilize these functions in their programs by including its library file.

Examples for library functions are

printf(), scanf(), sqrt(), abs(), fabs(), sin(), cos(), etc....

5.0.3 User-defined functions

These functions have to be developed by the user at the time of writing the program. The function name, meaning and the task of the function is decided by the user. However, a user-defined function can later become a part of the C library. Examples for user defined functions are main (), function to return area of circle. etc…

Example5.2: Program to read an integer and assign to another variable

void main(){ int a,b;

printf(“\n Enter an integer :” ); scanf(“%d”, &a); b = a; printf(“\n a=%d b=%d”, a, b );

}

Example5.3: Function to find area of a circle

float area(float radius){

float a;a=3.14159*radius*radius;return(a);

}

5.1 Objectives

After going through this chapter students are able to

Understand the need of a function. Write their own functions for a task. Write simple programs using structured programming concept. Use library functions in their programs. Understand the use of global and local variables. Apply the storage classes of variables and functions.

5.2 Function Definition (structure of a function)

Page 4: c.p function

A function can be defined with the general form

Where

return_type: indicates the data type of a value returned by the function and it may be of any data type like int, float, double, void, array, structure, pointer etc…

function_name: is the name of the function given by the user and should follow the rules of an identifier.

arg1, arg2, arg3,……. : are the list of arguments used to pass information to the function. These arguments are called formal parameters.

Local_variables declaration: declaration of local variables if required inside the function body.

Executable statements 1,2….: indicates any executable statements that are written to perform the task of the function.

return(expression): Return statement that returns the value of expression to the calling portion of the program. Only one expression can be included in return statement. Thus a function can return only one value to the calling portion of the program

Example5.4: Function to return the sum of two integers

Note1: Any function be it library or user defined function will follow the same general form

Note2: The return-type and arguments in a function are optional. When a function does not return a value then its return-type is void and for the function with no arguments the function-name follows empty set of parentheses. With the combination of return-type and arguments the functions may be of different categories shown as follows.

return_type function_name (data type arg1, data type arg2…){

Local_variable declaration;Executable statement 1;Executable statement 2;…………………………………….…………………………………….…………………………………….return(expression);

}

int sum(int a, int b)

{

int s;

s=a+b;

return(s);

}

Return type Function_name List of arguments

Local variable deciaration

Excutable statement

Return statement

Page 5: c.p function

Example5.5: A function returns biggest of two integers

Example5.6: A function to display a given integer is even or odd number

Example5.7: A function to display the message “WELCOME”

Example5.8: A function to returns a mile in terms of kilometers

Advantages:

Every program must have a main function which indicates the start of the program execution. Writing all statements of a small task in main only is fine but if the main contains large number of statements say 100,1000,10000 lines for a big task, then it leads to a number of problems like

The program may become too large and complex. It is difficult to understand, debug and test. It is difficult to identify the faulty statement. Repetitions of same set of statements a number of times within the same program. It is difficult to update the program.

If such big program is divided into functional parts, then each part may be independently coded, compiled and later integrated into a single unit. These independently coded program modules are called subprograms. In C these subprograms are called functions and they have the following advantages.

It is easy to write, understand, debug and test a function. It is easy to locate and isolate a faulty function for further investigation. We can avoid writing redundant program code and hence length of the program is reduced.

int big( int x, int y){

if( x > y) return(x);

else return(y);

}

void odd( int n){ if( n%2 = = 0 ) printf(“\n the number %d is even”, n); else printf(“\n the number %d is odd”, n);}

void wel(void ){

Printf(“\n WELCOME \n”);}

float mile_kilo( void ){

return(1.6093440);}

Page 6: c.p function

If the program is divided into subprograms, each subprogram can be written by one or two members of the team rather than having the whole team to work on the complex program.

A function can be accessed in many programs.

5.3 Calling a Function

Every C program must have a function with the name main and may have one or more other functions. Calling of a function means referring its name in a statement for utilizing its purpose at that point. For example the following fun1 () is called in main function.

Example5.9: Program to display a message using function

void fun1(){

Printf(“\n My Name is Raju \n”);}

main(){

fun1( );}

Here the fun1() is termed as called function and the function main() is termed as calling function.

A function can be called by any other function but main cannot be called by other functions. Execution of the program begins with main irrespective of the order of the functions.

Example5.10:

main(){ ………..

fun3( ); ………..

}

void fun1( ){ ………….

………….}

void fun2( ){ ………….

fun1( ); ………….

}

void fun3( ){ ……………

fun2( );……………}

Here fun3( ) is called by main( ) and fun3( ) calls fun2( ) which calls fun1( ).

5.3.1 Calling function with no return value

Output

My Name is Raju

Page 7: c.p function

Since the function does not return any value, its call cannot be written in an expression but has to be by an independent statement. For example,

Example5.11:

void main(){

int x; h_line();

}

void h_line(){ int i;

for(i=0;i<10;i++)printf(“-“);

}

Exampple5.12:

void main(){

int x;

x=h_line();}

void h_line(){ int i;

for(i=0;i<10;i++)printf(“-“);

}

5.3.2 Calling function with a return value

Since the function will return a value its call is written in expressions like assignment expression, logical expression and as an argument of another function call. For example,

Example5.13: Example5.14:

void main() void main(){ float p,r=5.5,a; { float r=5.5

p=PI(); printf(“\npi value=%f”, PI()); a=PI()*r*r; printf(“\narea=%f”, PI()*r*r);

} }

float PI(){

return(3.14159);}

5.3.3 Calling a function with arguments

Wrong

Page 8: c.p function

The function call with arguments is used to pass the data to the called function by the calling function. The arguments in the function call are called actual arguments / parameters and arguments in the function header are called formal parameters or dummy arguments

Example5.15: Program to find sum of two integers using function

int sum(int a, int b) void main(){ int s; { int x=20,y=30,k;

s=a+b; k=sum(x,y);return(s); printf(“\nvalue=%d”,k);

} }

Here the arguments a, b are dummy arguments and the arguments x, y are actual arguments

Note1:

Dummy arguments must be a valid variable name only, where as actual argument may be a variable name, array name, a constant, an expression or it may be a function call which will return a value.

Example5.16:

void main()

{ int x=20,y=30,s1,s2,s3,s4;s1=sum(x,y);s2=sum(50,70);s3=sum(x-5, y+20);s4=sum(sum(x,30),sum(50,70));

}Note2:

The names of dummy arguments and actual argument may or may not be same. Whatever the names may be compiler allocate different memory locations for the actual and dummy arguments.Example5.17:

void fun1( int a ){

a+ = 5;printf(“\nvalue of dummy arguments after modification is ”);printf(“\n a=%d ”, a );

}

main(){ int x = 20;

printf(“\nvalue of actual argument x is”);printf(“\n x=%d ”,x );fun1(x);

}

In the calling function main ( ) the actual argument x = 20 is passed to the called function fun1( ). In its definition the formal parameter a is incremented by 5.

Passing data to a called function in two ways

Output

value of actual argument isx = 20value of dummy arguments after modification isa=25

Page 9: c.p function

i. Call by valueii. Call by reference

In call by value a copy of the values of actual arguments from calling function are passed to the formal parameters of the called function

Example5.18:

Output:

values of x and y before swapx=20 y=30values of x and y after swapx=20 y=30

Note: It is noticed that there is no change in the values of x and y of the function main after the call of the function swap. Because, the function swap interchanged the values of a and b in the copy and this change is not reflected in the original arguments x and y.

In call by reference the addresses of actual arguments are passed to the formal parameters. Since the formal parameters hold addresses, they must be declared as pointers.

Example5.19:

Output:

Values of x and y before swapx=20 y=30values of x and y after swapx=30 y=20

Note: since addresses of the actual parameters x and y are passed to the function swap, the interchange made by the function swap is reflected in the actual arguments

5.4 Function Prototypes (Function Declaration)

main(){ int x=20, y=30; printf(“\n values of x and y before swap”); printf(“\n x=%d y=%d”,x,y); swap (x, y); printf(“\n values of x and y after swap”);

printf(“\n x=%d y=%d’,x,y);}

20, 30 void swap(int a, int b)

{int temp;temp=a;a=b;b=temp;

}

20

30

20

1000

x

30

1500

y 20 30

4000

a

30 20

4500

b

30 20

1500

main(){ int x=20, y=30; printf(“\n values of x and y before swap”); printf(“\n x=%d y=%d”,x,y); swap (&x, &y); printf(“\n values of x and y after swap”);

printf(“\n x=%d y=%d’,x,y);}

1000

, 1500 void swap(int *a, int *b){

int temp;temp=*a;*a=*b;*b=temp;

}

1000 1500

20 30

1000

x y 1000

4000

a

1500

4500

b

Page 10: c.p function

Consider an example5.20: write a function to return area of a circle and call this function in main to find area of a given circle

Example5.20: Program to find area of a circle using function

float area( float radius){

return(3.14159*radius*radius);}void main(){

float r,a;printf(“\n Enter radius of circle:”);scanf(“%f”,&f);a=area(r);printf(“\n area value=%f”,a);

}

Since the definition of the called function area appears before the calling function there will be no syntax error, as the function area is compiled before main.

But the convention is to write the definition of the calling function before the called function shown as follows.

void main(){

float r,a;printf(“\n Enter radius of circle:”);scanf(“%f”,&r);a=area(r);printf(“\n area value=%f”,a);

}

float area( float radius){

return(3.14159*radius*radius);}

In this case as the function main is compiled first, compiler assumes that area is the name of a function that returns an integer value. But in the function header

float area( float radius)

In this the function header declares that the function area returns a floating point type value and hence a type mismatch error will occur. To avoid this error we give advance information to the compiler about the type of value returned by the function and the type of arguments. This is achieved by writing the function prototype before definition of the main.

The general form of declaration of a function prototype is

Page 11: c.p function

Function prototype is required for all the functions except the functions of return_type int.

Example5.21: Program to find area of a circle using function

float area(float radius); //Function prototypevoid main(){float r,a;printf(“\n Enter radius of circle:”);scanf(“%f”,&r);a=area(r);printf(“\n area value=%f”,a);}

float area( float radius){return(3.14*radius*radius);}

Example5.22: Program find median of a list of numbers using a function to sort the list of numbers.

void bub_sort( int n, float a[10]); // Function prototypevoid main(){int n,i;float a[10], median;printf(“\n Enter the no of values:”);scanf(“%d”, &n);printf(“\nEnter the values”)for(i=0; i<n; ++i)

scanf(“%f”, &a[i]);bub_sort(n,a);

if(n%2)median = a[(n-1)/2];elsemedian = (a[n/2] + a[n/2-1])/2;

printf(“\n median =%.2f”, median);

}void bub_sort(int n, float a[10]){int p,j; float temp;for (p=1; p<n; ++p){for(j=1; j<n-p; ++j){if(a[j]>a[j+1]){temp= a[j];a[j] = a[j+1];

return_type function_name(type arg1, type arg2,……….);

Page 12: c.p function

a[j+1] = temp;}}}}

5.5 Categories of Functions

Based on the arguments present or not and a value is returned or not, the function may belong to one of the following categories.

1. Functions with arguments and return value2. Functions with arguments and no return value3. Functions with no arguments and return value4. Functions with no arguments and no return value

5.5.1 Functions with arguments and return value

Functions with arguments means, it is required to pass the required data from the calling function and with return value means, the calling function will receive a value of type return_type from the called function.

i.e. the data is passed from the calling function to the called function and the called function return a value to the calling function. The general form of this function is

return_type function_name (type arg_1, type arg_2,………., type arg_n){ …………………….. ……………………..

……………………..return(expression);}Example5.23 Function to return simple interest for any given values of principle in rupees, time in

years and rate of interest

float simple_intrest(float principle, float time, float rate ){ float I;

I = principle * time * rate/100;return( I);

}

Example5.24: Function to return area of a circle.

float area(float radius){

float a;a=3.14159*radius*radius;return(a);

}

5.5.2 Functions with arguments and no return value

Functions with arguments means, it is required to pass the required data from the calling function and functions; with no return value means the called function does not return any value to the calling function. In this case the return data type is void.

The general form of this type of function is

void function_name (type arg_1, type arg_2,………., type arg_n){ ……………………..

Page 13: c.p function

…………………….. ……………………..

return; }Example5.25: Function to print simple interest for any given values of principle in rupees, time in years

and rate of interest

void simple_intrest(float principle, float time, float rate ){ float I;

I = principle * time * rate/100;printf( “\n simple interest = %.2f”, I);

}

Example5.26: Function to print the given title.

void title(char str[] ){

printf (“%s”, str);return;

}

5.5.3 Functions with no arguments and return value

Functions with no arguments means, it is not required to pass any data from the calling function and with return value means, the calling function will receive a value of type return_type from the called function.

i.e. there is no data is passed from the calling function to the called function but a value is returned by the called function. The general form of this function is

return_type function_name ( ){ ……………………..

…………………….. ……………………..

return(expression);}

Eample5.27: Function to return pi value

float pi ( void){

return(3.14159);}

Example5.28: Function to return strength of a class

int strength(void){

return(65);}

5.5.4 Functions with no arguments and no return value

Page 14: c.p function

Functions with no arguments means, it is not required to pass any data from the calling function and functions with no return value means; the called function does not return any value to the calling function. In this case the return data type is void

The general form of this type of function is

void function_name (void){ …………………….. …………………….. ……………………..

return;}

Example5.29: Function to print simple interest for given principle, time and rate of interest

void simple_intrest( void){ float principle, rate, time, intrest;

printf(“\nEnter the principle, rate and time:”);scanf(“%f%f%f”, &principle, &rate, &time);intrest = principle*rate*time/100;printf( “\n simple interest = %.2f”, intrest);

}

Example5.30: Function to print the title “K L University”

void title(void){ printf (“K L University”);

return;}

5.6 Built-In Functions

In C library several functions are available to perform various tasks like data input/output, calculation of the values of mathematical functions, string manipulations, etc….which are needed in writing different application programs. These functions are called library functions or built-in functions. Since a large number of built-in functions are available they are classified into different categories and their headers are stored in different header files

Some of the header files corresponding to C standard libraries are

math.h – contains the headers of mathematical functions and macros stdio.h – contains the headers of standard input and output functions and macros string.h – contains the functions for string manipulation and processing conio.h – contains the headers of console input/output functions ctype.h – contain the headers of character type and manipulation functions

………………

Some of the built-in functions stored in their header files are

Page 15: c.p function

Sno Header file Function Use of the function1

math.h

abs( ) Gets the absolute value of an integer2 fabs( ) Gets the absolute value os a real value3 sqrt( ) Calculates the positive square root of the input value4 sin( ) Computes the sign of the input value5 cos( ) Computes the cos of the input value6 tan( ) Calculates the tangent of the input value7 asin( ) Computes the arc sin of the value8 acos( ) Computes the arc cosine of the input value9 atan( ) Calculates the arc tangent of the input value

10 exp( ) Calculates e to the x the power11 pow( ) Calculates x to the power y12 log( ) Calculates natural logarithm of input value13 log10( ) Calculates bse10 logarithm of input value14

stdio.h

scanf() To read input data in a given format through key board15 printf( ) To display data in a given format on the screen16 getchar( ) To read a character through key board17 putchar( ) To display a character on the screen18 gets( ) To read a string through key board19 puts( ) To display string on the screen20 flushall( ) Clears all buffers associated with open input stream21

string.h

strlen( ) Calculates length of a string22 strcpy( ) Copies one string into another string23 strcmp( ) Compares two strings24 strcat( ) Joins two strings together

abs( ) its prototype is int abs( int x);fabs( ) its prototype is double fabs(double x);

Example5.31:

int x= -1234, y;double r=5.45, s;y=abs(x);s=fabs(r);

sqrt( ) its prototype is double sqrt(double x);

Example5.32:

double x=4.0, result;result = sqrt(x);

sin( ) its prototype is double sin(double x); where x in radianscos( ) its prototype is double cos(double x); where x in radianstan( ) its prototype is double tan(double x); where x in radians

Example5.33:

float x=0.5, angle=60, x1,x2,x3,a1,a2,a3;

Page 16: c.p function

x1=sin(x);x2=cos(x);x3=tan(x);a1=sin(3.14159*angle/180);a2=cos(3.14159*angle/180);a3=tan(3.14159*angle/180);

exp( ) its prototype is double exp(double x); pow( ) its prototype is double pow(double x, double y);log( ) its prototype is double log(double x);log10( ) its prototype is double log10(double x);

Example5.34:

Double p=8.687, x=2.0, y=3.0, r1,r2,3;r1 = exp(p);r2 = log(p);r3 = pow(x,y);

5.7 Recursion

5.7.1 What is recursion?

Calling of a function by itself repeatedly until a condition is satisfied is called recursion.

Example5.35:

void fun1(){

--------fun1();--------

}

Example5.36:

void main(){

printf(“\nKLU”);main();

}

5.7.2 How to write a recursive function

Output

KLUKLUKLUKLU…….……. Infinite number of times ( “KLU” is displayed infinite number of times)

Page 17: c.p function

Since recursion process simulates repetitive process, it is required to check a condition for stopping or repeating the process. A recursive function has two parts.

i. Base partii. Recursive part

The code written for stopping the repetitive process is the base part and the code written for repeating the same function call is called recursive part

Example5.37: Recursive function to find factorial of an integer

Factorial of an integer is a recursive function in Mathematics and is defined as follows

n!= 1 , if n=0 or 1 = n(n-1)! , if n>1

Using this mathematical function we can write the corresponding C code.

long int factorial ( int n){ long f;

if (n==0 ) f=1;else f= n*factorial(n-1);return(f);

}

Explanation:

long int factorial( int n );

n=0f= 1

n=1f=1 x 0!

n=2f=2 x 1!

n=3f=3 x 2!

n=4f=4 x 3!

n=5f=5 x 4! f=120

f=24

f=6

f=2

f=1

f=1

Stack

Call-1

Call-2

Call-3

Call-4

Call-5

Call-6

Calling function

Assume n = 5. Since the value of n is not 1, the statement

f = n * factorial (n-1);will be executed with n = 5 that is

f = 5*factorial (4);will be evaluated. The expression on the right-hand side includes a call to factorial with n = 4 this call will return the following value.

4*factorial (3)Once again, factorial is called with n = 3, 2, 1 and 0, when n = 0 the function returns 1. The sequence of operations can be summarized as follows:

f = 5*factorial(4) = 5*4*factorial(3) = 5*4*3*factorial(2) = 5*4*3*2*factorial(1) = 5*4*3*2*1*factorial(0) = 5*4*3*2*1*1 = 120

Page 18: c.p function

void main( ){ int n,f;

printf(“\n Enter a number:”);scanf(“%d”, &n);f=factorial(n);printf(“\n factorial of given num %d is %”, n, f);

}long int factorial(int n){ long int f;

if(n==0) f=1;else f=n*factorial(n-1);return(f);

}

OutputEnter a number: 5Factorial of given num 5 is 120

5.8 Storage classes

5.8.1 Global & Local VariablesVariables declared in programs may be classified into two categories

1. Local variables 2. Global variables

In the programs written earlier variables are declared inside of the functions. Such variables are called local variables, However, variables may be declared outside the scope of a function such variables are called global variables.

Local Variables:

Local variables scope is confined within the block or function where it is defined. ie.they are recognized within the block or the function

If the local variable is not initialized in the declaration it is initialized with garbage by the system

As soon as the execution of the block starts the local variable becomes active and at the end of the execution it is destroyed.

Example5.38:

main()

{ int i=4; int j=10;

i++;if (j > 0){int i=100; printf("value of i inside the block = %d\n",i); }printf("value of I outside the block= %d\n",i);

}

Output

value of i inside the block = 100value of i outside the block=5

Page 19: c.p function

Global Variables

Scope of the global variables is from the point of declaration through the remainder of the program. i.e. any function which falls in their scope can access their values.

If the global variables declaration does not include initial values they are initialized by the system as follows:

Dattype initialserint 0char ‘\0’float 0pointer NULL

If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use same name for both global and local variable.

Example5.39:

int i=4; /* Global definition */main() { i++; /* Global variable scces */ func(); printf( "Value of global varaible i = %d\n", i ); } func() { int i=10; /* Local declaration of i */ i++; printf( "Value of local variable in the function func i = %d\n", i ); }

Note: differences between local and global variables

OutputValue of local variable in the function func i = 11Value of global variable i = 5

Local variables

Variables declared inside a function are called local variables.

For examplevoid main( ) { int x,y;

……..……..

}

Local variable can be accessed only within the function in which it is defined

Variables defined in one function cannot be accessed in other functions.

Local variables do not retain their values once the control has been transferred out of the defining function.

Values of local variable cannot be modified by other functions except the function in which it is defined.

If the values of local variables are needed by other functions they must be passed through arguments in the function call

Global variables

Variables declared outside a function are called global variables.

For exampleint x,y;void main( ){ …….

…….}

Global variable can be accessed throughout the program

Global variables can be accessed by any function which falls in their scope.

Global variables can retain their values though out the execution of the program

Values of global variable can be modified by other functions which fall in its scope.

x2:/without y word extern ollowing program not accessed i ables are destroied.

Since the global variables are recognized by any function within their scope their values need not be passed through arguments

Usage of global variables is a convenient mechanism for returning multiple values

Page 20: c.p function

5.8.2 Storage Classes

Each Variable in C is characterized by its

i. data type ii. storage class

Data type refers the type of data to be stored in a variable. For example integer variables used to store integer data items, float variables used to store real numbers

int x,y; // x and y are integer variables and represent integer datafloat r; // r is a float variable and represent floating point type data

Storage class refers to the scope and longevity of a variable. It also describes the

default initial value and memory location

The scope actually determines the portion of the program that, the variable is recognized.

The lifetime of the variable determines how long the variable is alive or active.

Page 21: c.p function

There are four different storage classes in C and they are represented by the keywords

auto - automatic variables, extern - external variables, static - static variables and register - register variables.

The general form of variable declaration with storage class is

For exampleauto int x; // x is an automatic integer variablestatic float y // y is static floating point variable

5.8.2.1 Automatic variables

The automatic variables are declared inside a function or a block

void main(){ auto int x,y; //x and y are automatic variables

……………….………………..

}

However, local variables without any storage class specifier have the default storage class auto

void fun1(){ int c,k; // c and k are automatic variables

………..}

Scope: The scope of automatic variables is local to the function in which it is defined.

Life time: The lifetime of automatic variable is temporary. i.e. it is defined when a function is called for execution and is destroyed when the control is exited from its defining function

Since x is automatic variable and is reinitialized with 10 in every call of fun1( ). Hence, fun1( ) returns same value 11 to main( ) in every call.

Default initial value: The default initial value of automatic variable is garbage

Storage_class data_type variable_name1, variable_name2,…..;

Output

y= garbage

void main( ){ int y; printf(“\n y=%d”, y+=5);}

void main( ){ int i; for(i=1; i<5; i++) printf(“%d\n”, fun1( ));}

int fun1( ){ x=10;

return(++x);}

Output

x=11x=11x=11x=11

Page 22: c.p function

Since y is automatic variable and is not initialized, its default initial value is garbage. Automatic variables can be initialized with expressions. For example,

int a=10, b=5, c = a+b; is allowed.

Memory location: These variables are located in main memory.

Note1: Variable defined in one function is not accessible in any other function.

Example5.40:void main(){ int x=25;

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

void fun1(){ int y=50;

Printf(“\n x=%d”,x);Printf(“\n y=%d”, y);

}

void fun2(){ x=1000;

Y=2000;}

Note2: If the name of global and local variables is same then in the scope of local variable the first priority is for local variables. In such cases the value of global variable is temporarily put on shelf and beyond the scope of local variable again the global variable is active.

Example5.41: what is the output of the following program?

5.8.2.2 External variables

Variables that are declared outside the scope of any function are external variables. All global variables are external variables.

x- is local to main( ) but not accessed in fun1( )

x- is local to main( ) and y- is local to fun1( ) but not accessed in fun2( )

int x = 100;main(){

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

if(x>=100){int x = 10;

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

Printf(“\n x=%d”, x);}

Scope of x global

Scope of a local

Scope of x local

Output

x=100x=10x=100

The global variable x=100 is not accessed here because of scope of local variable x=10

Page 23: c.p function

int s;void main(){ s=96; // s is global variable………..…………}

float r;void fun1(){r=5.4; // r is global variable……….}

Scope: The scope of external variables extends from the point of definition through the remainder of the program

Life time: The lifetime of global variables is permanent i.e. they retain their values throughout the execution of the program

Default initial value: The default initial value of external variable is zero. External variables cannot be initialized with expressions for example,

int a=5, b=10, c=a+b; is not allowed, if a,b,c are external variables

Memory location: These variables are located in main memory.

Note1: Since external variables are recognized globally, they can be accessed from any function that falls within their scope, thus, an external variable can be assigned a value within one function, and this value can be used within another function.

Example5.42: what is the output of the following program?

int s=96;void main( ){

printf(“\n x=%d”x)’fun1();fun2();printf(“\n x=%d”,x);

}void fun1( ){ x=200;

printf(“\n x=%d”, x);}void fun2(){ printf(“\n x=%d”,x);

x=500; }

Note2: If a global variable is accessed before its point of definition then it needs to be declared as it is an external variable using the key word extern

Example5.43: what is the output of the following program

void main( )

Output

x=96x=200x=200x=500

External variable declaration (memory not allocated)

Page 24: c.p function

{ extern int X;printf(“\n X=%d”, X );fun1();

}

int X;void fun1(){

X=200;frintf(‘\n X=%d”, X );

}

Declaration Vs definition

The external declaration of X inside the function main informs the compiler that X is an integer type defined somewhere else in the program. Note that the extern declaration does not allocate storage space for variable where as variable definition X outside the function does allocate storage space for variable.

The assignment of initial values can be included within an external variable definition it defines. Whereas the external variable declaration cannot include initial values as no storage space is allocated.

The storage class specifier extern is not required in an external variable definition, whereas external declaration must begin with the storage class specifier extern.

5.8.2.3 Static variables

For some applications it is needed to retain the value of a variable even after the control is exited from the function. For this purpose variables of static storage class are used. Static variables are initialized only once even though the function may be called more than one time.

Static variables may be for internal variables or external variables.

Internal static variables are declared inside a function using the key word static. Whereas external static variables are declared outside of a function using the key word static.

static int c; // c is static externalint s; // s is externalvoid main(){ static auto int x; //x is static internal variable

int i,j; // i and j are automatic variables……………….………………..

}void fun1(){ static int c,k; // c and k are static internal variable

………..}

Output

X=200X=200

External variable definition (memory is allocated)

Page 25: c.p function

Scope: The scope of static internal is local to the function in which it is defined and the scope of static external variable is from the point of declaration through the remainder of the program

Life time: The lifetime of static variables is permanent. Internal static variables retain their values even if the control is exited from the function

Example5.44: what is the output of the following program

The internal static variable x initialized only once at compilation time. Since it retains its values

during successive function calls the values returned by fun1( ) to the function main( ) are 11, 12,

13 and 14 in the first, second, third and fourth calls.

Default initial value: The default initial value of internal or external static variable is zero

Since x and y are static variables they are initialized with zero rather than garbage.

Memory location: Both these variables are located in main memory. The difference between static external variable and a simple external variable is that the static

variable is available only within the file where it is defined , while the simple external variable

can be accessed by other files.

5.8.2.4 Register variables

A variable is usually stored in the main memory

It is possible to tell the compiler that a variable should be kept in the CPU registers by defining it as register variable.

void main( ){ int i; for(i=1; i<5; i++) printf(“%d\n”, fun1( ));}

int fun1( ){ static x=10;

return(++x);}

Output

x=11x=12x=13x=14

Output

x=1y=5

static int x;void main( ){ static int y; printf(“\n x=%d”, ++x); printf(“\n y=%d”, y+=5);}

Page 26: c.p function

Since a register access is much faster than memory access, keeping the frequently accessed variables (like loop control variables) in the register will make the execution of the program faster.

Except the memory space allocation all the other properties of register variables are similar to that of automatic variables.

Very few variables can be placed in the register. Normally two or three per function.

Only local variables of type int, char can be declared with the keyword register

void main( ){

register int i; // i is register variable.…………………for(i=0; i<=10000; i++) { }………………..………………...

}

Scope: The scope is local to the function in which it is defined.

Life time: The life time of register variables is temporary

Default initial value: The default initial value is garbage

Memory location: These variables are located in registers of CPU

5.9 Summary

A function is a module or block of program code which deals with a particular task. Making functions is a way of isolating one block of code from other independent blocks of code.

A function can take a number of parameters, do required processing and then return a value. There may be a function which does not return any value, but perform a given task.

You already have seen couple of built-in functions like printf( ); Similar way you can define your own functions in C language.

Consider the following chunk of code

int total = 20;

printf(“Hellow World”

total = total+1;

To turn it into a function you simply wrap the code in a pair of curly brackets to convert it into a single compound statement and write the name that you want to give it in front of the brackets:

Demo( ){ int total = 20; printf("Hello World"); total = total + l;}

Curved brackets after the function's name are required. You can pass one or more parameters to a function as follows:

Page 27: c.p function

Demo( int a, int b){ int total; printf("Hello World"); total = a + b;}

By default function does not return anything. But you can make a function to return any value as follows:

int Demo( int a, int b){ int total; printf("Hello World"); total = a + b; return total;}

A return keyword is used to return a value and datatype of the returned value is specified before the name of function. In this case function returns total which is int type. If a function does not return a value then void keyword can be used as return value.

Once you have defined your function you can use it within a program:

main(){ int s; s=Demo(20,30);}

Each function behaves the same way as C language standard function main(). So a function will have its own local variables defined. In the above example the variable total is local to the function Demo.

A global variable can be accessed in any function in a similar way as it is accessed in main() function.

When a function is defined at any place in the program then it is called function definition. At the time of definition of a function actual logic is implemented with-in the function.

A function declaration does not have any body and they just have their interfaces.

A function declaration is usually declared at the top of a C source file, or in a separate header file.

A function declaration is sometime called function prototype. For the above Demo() function which returns an integer, and takes two parameters a function declaration will be as follows:

int Demo( int a, int b);

A function can be called recursively. The following code prints the word Hallow repeatedly because the main( ) is called recursively

void main( ){ printf(“Hallow”); main();}

A recursive function code involves if....else control to decide whether the recursive call is to be continued or to be stop. The following code prints the output 0 1 2

Page 28: c.p function

void f( ){ static int x; if(x==3) return; else { printf(“ %d”, x); x++; f( ); }}

There are two ways to pass parameters to a function:

Pass by Value: mechanism is used when you don't want to change the value of passed paramters. When parameters are passed by value then functions in C create copies of the passed variables and do required processing on these copied variables.

Pass by Reference mechanism is used when you want a function to do the changes in passed parameters and reflect those changes back to the calling function. In this case only addresses of the variables are passed to a function so that function can work directly over the addresses.

5.10 Review questions

1. What is the need for functions?

2. Explain the general form of defining a function.

3. What do you mean by function call?

4. What are formal arguments?

Page 29: c.p function

5. What are actual arguments?

6. Define function prototype.

7. Mention the categories of functions.

8. What is calling function?

9. What is a called function?

10. The number of actual arguments and the number of formal arguments should be same when a

function is called. True / False

11. One function can be defined within another function. True / false

12. How many values can a function return?

13. What is meant by the scope of a variable?

14. What is meant by lifetime of a variable?

15. Mention different storage classes.

16. Define recursion and a recursive function

17. A function can returns float value by default. True / False

18. Variables declared within functions are by default of static storage class. True / False

19. The name of global variable and that of a local variable can be same. True / False

20. Only local variables can be of register storage class. True / False

21. Static variables retain their values between function calls. True / False

22. Write about storage classes in C along with their location, scope and life span.

5.11 Programming Exercise

1. Write a function that converts miles to kilometers. Note that 1 mile equals 1.6093440 km.

2. Write a function that will round a floating-point number. For example the number 17.457 would

yield the value 17.46 when it is rounded off to two decimal places.

3. Write a recursive function to find the binary code of a number.

4. Write a program to find the reverse of a number using function

Page 30: c.p function

5. Write a function prime that returns 1 if its argument is a prime number and returns zero

otherwise.

6. Write a function to evaluate the formula y = xn where y and x are floating-point variables and n

is an integer variable

7. Calculate factorials n! for n from 1 to 20 using a factorial function with return type of unsigned

long long.

8. Discuss how parameters are passed between functions in C by writing a function ‘SWAP’ to

exchange the values of two integers passed to it by the main( ) function.

9. Write a function sort to sort a list of values and call this function in main to find the median of a

list of n numbers

10. Write a program to reverse a integer using a recursive function

11. The Fibonacci numbers are defined recursively as follows

F1 = 1

F2 = 1

Fn = Fn-1 + Fn-2 if n>2

i) Write a recursive function that will find n th element of the Fibonacci sequence

ii) Write a function with local static variables to find n th element of Fibonacci sequence

12. Write a recursive function for binary search with function prototype int binsearch( int n,

double data[], double key ); and call this function in main to test binary search function

13. Write a recursive function to find gcd of two numbers, use this function to find their lcm

How to write programs using functions

To write a function for a given task programmer has to use general form of one of the categories.

Functions with ordinary variables

A function with ordinary variables involves defining functions with ordinary variables as list of arguments. For example,

Program:1

Page 31: c.p function

Write a function to return factorial of a number and call this function in main to find the value of the Binomial coefficient c(n,r)

#include<stdio.h>long int factorial(int n);void main(){

int n,r;long ncr;printf(“\n Enter the values of n and r :”);scanf(“%d%d”, &n, &r);ncr = factorial(n)/(factorial( r )*factorial(n-r));printf(“\n c(%d, %d) = %ld”, n, r, ncr);

}

long factorial(int n){

long f=1;int i;for(i=1; i<=n; i++)f = f * i;return(f);

}

Program:2

Write a function to return GCD of two numbers and call this function in main to find GCD and LCM of

four given numbers;

#include<stdio.h>void main(){

int n1,n2,n3,n4,gc1,gc2,gc,lc1,lc2,lc;printf(“\n enter any four integers:”);scanf(“%d%d%d%d”,&n1,&n2,&n3,&n4);gc1=gcd(n1,n2);gc2=gcd(n3,n4);gc=gcd(gc1,gc2);lc1=n1*n2/gc1;lc2=n3*n4/gc2;lc=lc1*lc2/gcd(lc1,lc2);printf(“\n GCD=%d and LCM=%d”,gc,lc);

}

int gcd(int a, int b){ int r;

do{ r=a%b;

if(r==0)return(b);

else{ a=b;

b=r;}

Page 32: c.p function

} while(r!=0);}

Program:3

Write a function power that computes x raised to the power y for integers x and y and returns double-

type value.

#include<stdio.h>double power(int x, int y);void main(){

int x,y; float p;printf(“\n enter any two integers:”);scanf(“%d%d”,&x,&y);if(y>0)

p=power(x,y);else

p = 1.0/power(x,y);printf(“\n value of %d to the pow %d is %ld”,x,y,p);

}

long power(int x,int y){

long p=1;while(y--)

p*=x;return(p);

}

Functions with One-Dimensional Arrays:

Like the values of ordinary variables, we can pass arrays to a function when a function is defined with one-dimensional array as formal parameter. To pass one-dimensional array to a called function, simply refer the name of array as actual argument without any subscripts, and size of array.

Program:4

Write a function to return largest of a list of integers and call this function in main to find largest of a given list of values.

#include<stdio.h>int max(int a[50], int n);void main(){

int a[50], larg,i,n;printf(“\n Enter no of elements in list”);scanf(“%d”,&n);printf(“\n Enter %d no of elements:”,n);for(i=0; i<n; i++)

scanf(“%d”,&a[i]);

Page 33: c.p function

larg=max(a,n);printf(“\n largest of the list is %d”, larg);

}

int max(int a[50], int n){ int i,big;

big=a[0];for(i=1; i<n; i++){

if(big<a[i])big=a[i];

}return(big);

}

Program5: Write a program that uses a function to sort an array of integers.

#include<stdio.h>void sort(int a[50], int n);void main(){

int rank[50],i,n;printf(“\n enter the no of elements in the array:”);scanf(“%d”,&n);printf(“\n enter %d no of elements:”,n);for(i=0;i<n;i++)

scanf(“%d”,&rank[i]);printf(“\n\nElements before sort:\n\n”);for(i=0;i<n;i++)

printf(“%5d”,rank[i]);sort(rank,n);printf(“\n\n Elements after sort:\n\n”);for(i=0;i<n;i++)

printf(“%5d”,rank[i]);}

sort(int x[50], int n){

int i,j,temp;for(i=0; i<n-1; i++){

for(j=i+1; j<n; j++){

if(x[i]>x[j])

Page 34: c.p function

{temp=x[i];x[i]=x[j];x[j]=temp;

}}

}}

Program6:

Write a program to print elements of an array in reverse order using function

#include<stdio.h>void print_rev(int a[ ], int );void main(){

int a[50],n,i;printf(‘\n Enter no of elements in the array:”);scanf(“%d”,&n);printf(“\n Enter %d number of elements:”,n);for(i=0;i<n;i++)

scanf(“%d”,&a[i]);printf(“\nElements in reverse order:\n”);print_rev(a,n);

}

void print_rev(int a[], int n){

int i;for(i=n-1;i>=0;i--)

printf(“%5d”,a[i]);}

Functions with Two-Dimensional Arrays:

To pass multi-dimensional array to a function we should fallow the following rules In the function definition, the formal parameter must be two-dimensional array by indicating

two subscripts. The size of second subscript must be specified. The prototype declaration should be similar to the function definition The function must be called simply by passing the array name only.

Program7: Using functions write a program to read elements into two-dimensional array and print the elements on the screen in matrix form

#include<stdio.h>void read_mat(int a[10][10], int r, int c);void print_mat(int a[10][10], int r, int c);void main(){

Page 35: c.p function

int a[10][10],m,n;printf(“\n Enter no of rows and calms of matrix:”);scanf(“%d%d”,&m,&n);printf(“\n Enter %dX%d number of elements:\n”,m,n);read_mat(a,m,n);printf(“\n Elements in matrix form:\n”);print_mat(a,m,n);

}

void read_mat(int a[10][10], int r, int c){ int i,j;

for(i=0; i<r; i++)for (j=0; j<c; j++)

scanf(“%d”, &a[i][j]);}void print_mat(int a[][10], int r, int c){ int i,j;

for(i=0; i<r; i++){ for(j=0; j<c; j++)

printf(“%5d”,a[i][j]);printf(“\n”);

}}

Program8:

Write a program for addition of two given matrices and display the elements on the screen using functions.

#include<stdio.h>void add_mat(int a[10][10], int b[10][10], int c[10][10], int r1, int c1, int r2, int c2);void main(){

int a[10][10], b[10][10], c[10][10], m1, m2, n1, n2;printf(“\n Enter the size of 1st matrix:”);scanf(“%d%d”, &m1, &n1);printf(“\n Enter the elements of 1st matrix:\n”);read_mat(a,m1,n1);printf(“\n Enter the size of 2nd matrix:”);scanf(“%d%d”, &m2, &n2);printf(“\n Enter the elements of 2nd matrix:\n”);read_mat(b,m2,n2);add_mat(a,b,c,m1,n1,m2,n2);

if(m1==m2&&n1==n2){

printf(“\n Elements after addition:\n”);print_mat(c,m1,n1);

}else

Printf(“\n addition is not possible”);}

Page 36: c.p function

void add_mat(int a[10][10], b[10][10], c[10][10], int r1, int c1, int r2, int c2)

{int i,j;if(r1==r2&&c1==c2){

for(i=0;i<r1;i++)for(j=0;j<c1;j++)

c[i][j]=a[i][j]+b[i][j];}

}

Program9:

Write a program for multiplication of two given matrices using functions.

#include<stdio.h>void mult_mat(int a[10][10], int b[10][10], int c[10][10], int r1, int c1, int r2, int c2);void main(){

int a[10][10],b[10][10],c[10][10],m1,m2,n1,n2;printf(“\n Enter the size of 1st matrix:”);scanf(“%d%d”,&m1,&n1);printf(“\n Enter the elements of 1st matrix:\n”);read_mat(a,m1,n1);printf(“\n Enter the size of 2nd matrix:”);scanf(“%d%d”,&m2,&n2);printf(“\n Enter the elements of 2nd matrix:\n”);read_mat(b,m2,n2);if(n1==m2){ mult_mat(a,b,c,m1,n1,m2,n2);

printf(“\n Elements after multiplication:\n”);print_mat(c,m1,n2);

}else

printf(“\n multiplication is not possible”);}

void mult_mat(int a[10][10], b[10][10], c[10][10], int r1, int c1, int r2, int c2)

{int i,j,k;if(c1==r2){

for(i=0; i<r1; i++)for(j=0;j<c2;j++)

{c[i][j]=0;for(k=0;k<c1;k++)

Page 37: c.p function

c[i][j]+=a[i][k]*b[k][j];}

}

}

Functions with String variables:

The strings variables deals with the char type of arrays in C and it may one-dimensional char variable or multi-dimensional char variable

Passing one-dimensional char variable to a called function:

To pass one-dimensional char variable as actual argument simply refer its array name but in function definition the formal parameter must be defined along with single subscript and size.

Program10: Write a program to read a string constant though terminal and display on the screen using functions.

#include<stdio.h>void read_str(char str[]);void print_str(char str[]);void main(){ char str[20];

read_str(str);print_str(str);

}

void read_str(char str[20]){

printf(“\n Enter a string:”);flushall()gets(str);

}

void print_str(char str[20]){

Printf(“\n the sring is\n”);puts(str);

}

Passing Two-dimensional char variable to a called function:

To pass two-dimensional char variable as actual argument simply refer its array name but in function definition the formal parameter must be defined along with its two subscripts and sizes.

Program11. Write a program to read a list of names using terminal and display the list on the screen using functions.

#include<stdio.h>void read_list(char list[20][20], int );void print_list(char list[20][20], int);void main()

Page 38: c.p function

{char list[20][20];int n;printf(“\n Enter no of names in the list:”);scanf(“%d’,&n);printf(“\n Enter %d no of names:\n”,n);read_list(list,n);printf(“\n List of names is\n”);print_list(list,n);

}

void read_list(char list[20][20], int n){

int i;for(i=o; i<n; i++){

printf(“\n Enter the name:”);flushall();gets(list[i]);

}}

void print_list(char list[20][20], int n){

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

puts(list[i]);}