c.p function
Upcoming SlideShare
Loading in...5
×
 

c.p function

on

  • 541 views

concept of functions

concept of functions

Statistics

Views

Total Views
541
Views on SlideShare
541
Embed Views
0

Actions

Likes
1
Downloads
19
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    c.p function c.p function Document Transcript

    • CHAPTER -5 FUNCTIONSContents: 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
    • 5.0 Introduction5.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 findarea of a circle. Now we can understand what is a functionA 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 numbersHere the task of each example is different and writing the set of statements is also independent to eachother.Generally a C program consists of one or more modules called functions, one of these functions must becalled main. Execution of the program will always begin by carrying out the instructions in main. Otherfunctions 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 functions5.0.2 Library functionsWhich are already predefined in the system and stored in C Library files. The meaning and purpose ofthese functions are fixed. It is not possible to change its meaning and purpose by the user, but user canutilize these functions in their programs by including its library file.Examples for library functions areprintf(), scanf(), sqrt(), abs(), fabs(), sin(), cos(), etc....5.0.3 User-defined functionsThese 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 laterbecome a part of the C library. Examples for user defined functions are main (), function to return areaof 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 ObjectivesAfter 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)A function can be defined with the general form return_type function_name (data type arg1, data type arg2…) { Local_variable declaration; Executable statement 1; Executable statement 2; ……………………………………. ……………………………………. ……………………………………. return(expression); } 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. Return type Function_name List of arguments • Executable statements 1,2….: indicates any executable statements that are written to perform the task of the function. • return(expression): Returna,statement that returns the value ofvariable to the calling portion int sum(int int b) Local expression deciaration { 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 int s; Excutable statement s=a+b; Example5.4: Function to return the sum of two integers return(s); } Return statement
    • Note1: Any function be it library or user defined function will follow the same general formNote2: The return-type and arguments in a function are optional. When a function does not return avalue then its return-type is void and for the function with no arguments the function-name followsempty set of parentheses. With the combination of return-type and arguments the functions may be ofdifferent categories shown as follows.Example5.5: A function returns biggest of two integers int big( int x, int y) { if( x > y) return(x); else return(y); }Example5.6: A function to display a given integer is even or odd number 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); }Example5.7: A function to display the message “WELCOME” void wel(void ) { Printf(“n WELCOME n”); }Example5.8: A function to returns a mile in terms of kilometers float mile_kilo( void ) { return(1.6093440); }
    • Advantages:Every program must have a main function which indicates the start of the program execution. Writingall statements of a small task in main only is fine but if the main contains large number of statementssay 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 calledsubprograms. 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. • 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 FunctionEvery 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. Forexample 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”); Output } My Name is Raju 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. Executionof 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 valueSince the function does not return any value, its call cannot be written in an expression but has to be byan 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() { Wrong 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 valueSince 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 argumentsThe 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 thefunction header are called formal parameters or dummy argumentsExample5.15: Program to find sum of two integers using functionint 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 argumentsNote1: Dummy arguments must be a valid variable name only, where as actual argument may be a variablename, 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 namesmay 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 );} Outputmain() value of actual argument is{ int x = 20; x = 20 printf(“nvalue of actual argument x is”); value of dummy arguments after modification is printf(“n x=%d ”,x ); a=25 fun1(x);}In the calling function main ( ) the actual argument x = 20 is passed to the called function fun1( ). In itsdefinition the formal parameter a is incremented by 5.Passing data to a called function in two ways i. Call by value ii. Call by referenceIn call by value a copy of the values of actual arguments from calling function are passed to the formalparameters of the called functionExample5.18: 30 20 main() void swap(int a, int b) { 20 , 30 { int x=20, y=30; int temp; printf(“n values of x and y before swap”); temp=a; a=b; printf(“n x=%d y=%d”,x,y); b=temp; swap (x, y); } printf(“n values of x and y after swap”); a b printf(“n x=%d y=%d’,x,y); } x y 20 30 30 20 20 30 4000 4500Output: 1000 1500values of x and y before swapx=20 y=30values of x and y after swapx=20 y=30Note: It is noticed that there is no change in the values of x and y of the function main after thecall of the function swap. Because, the function swap interchanged the values of a and b in thecopy 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. 1500Example5.19: 1000main() , 1500 void swap(int *a, int *b){ 1000 { int x=20, y=30; int temp; printf(“n values of x and y before swap”); temp=*a; printf(“n x=%d y=%d”,x,y); *a=*b; swap (&x, &y); *b=temp; printf(“n values of x and y after swap”); } a b printf(“n x=%d y=%d’,x,y);} x y 1000 1500Output: 20 30 30 20 4000 4500Values of x and y before swap 1000 1500x=20 y=30values of x and y after swapx=30 y=20Note: since addresses of the actual parameters x and y are passed to the function swap, the interchangemade by the function swap is reflected in the actual arguments 5.4 Function Prototypes (Function Declaration)Consider an example5.20: write a function to return area of a circle and call this function in main tofind area of a given circleExample5.20: Program to find area of a circle using functionfloat 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 nosyntax 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 asfollows.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 functionthat returns an integer value. But in the function headerfloat area( float radius)In this the function header declares that the function area returns a floating point type value and hence atype mismatch error will occur. To avoid this error we give advance information to the compiler aboutthe type of value returned by the function and the type of arguments. This is achieved by writing thefunction prototype before definition of the main.The general form of declaration of a function prototype is return_type function_name(type arg1, type arg2,……….);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 functionfloat 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];a[j+1] = temp;}}}} 5.5 Categories of FunctionsBased on the arguments present or not and a value is returned or not, the function may belong to one ofthe following categories. 1. Functions with arguments and return value 2. Functions with arguments and no return value 3. Functions with no arguments and return value 4. Functions with no arguments and no return value5.5.1 Functions with arguments and return valueFunctions with arguments means, it is required to pass the required data from the calling function andwith return value means, the calling function will receive a value of type return_type from the calledfunction.i.e. the data is passed from the calling function to the called function and the called function return avalue to the calling function. The general form of this function isreturn_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 interestfloat 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 valueFunctions with arguments means, it is required to pass the required data from the calling function andfunctions; with no return value means the called function does not return any value to the callingfunction. 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) { …………………….. …………………….. ……………………..return; }Example5.25: Function to print simple interest for any given values of principle in rupees, time in years and rate of interestvoid 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 valueFunctions with no arguments means, it is not required to pass any data from the calling function andwith return value means, the calling function will receive a value of type return_type from the calledfunction.
    • i.e. there is no data is passed from the calling function to the called function but a value is returned bythe called function. The general form of this function isreturn_type function_name ( ){ …………………….. …………………….. ……………………..return(expression);}Eample5.27: Function to return pi valuefloat pi ( void){ return(3.14159);}Example5.28: Function to return strength of a classint strength(void){ return(65);}5.5.4 Functions with no arguments and no return valueFunctions with no arguments means, it is not required to pass any data from the calling function andfunctions with no return value means; the called function does not return any value to the callingfunction. In this case the return data type is voidThe general form of this type of function isvoid function_name (void){ …………………….. …………………….. …………………….. return;}Example5.29: Function to print simple interest for given principle, time and rate of interestvoid 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 FunctionsIn C library several functions are available to perform various tasks like data input/output, calculation ofthe values of mathematical functions, string manipulations, etc….which are needed in writing differentapplication programs. These functions are called library functions or built-in functions. Since a largenumber of built-in functions are available they are classified into different categories and their headersare stored in different header filesSome 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 Sno Header file Function Use of the function 1 abs( ) Gets the absolute value of an integer 2 fabs( ) Gets the absolute value os a real value 3 sqrt( ) Calculates the positive square root of the input value 4 sin( ) Computes the sign of the input value 5 cos( ) Computes the cos of the input value 6 tan( ) Calculates the tangent of the input value 7 math.h asin( ) Computes the arc sin of the value 8 acos( ) Computes the arc cosine of the input value 9 atan( ) Calculates the arc tangent of the input value 10 exp( ) Calculates e to the x the power 11 pow( ) Calculates x to the power y 12 log( ) Calculates natural logarithm of input value 13 log10( ) Calculates bse10 logarithm of input value 14 scanf() To read input data in a given format through key board 15 printf( ) To display data in a given format on the screen 16 getchar( ) To read a character through key board 17 stdio.h putchar( ) To display a character on the screen 18 gets( ) To read a string through key board 19 puts( ) To display string on the screen 20 flushall( ) Clears all buffers associated with open input stream 21 strlen( ) Calculates length of a string 22 strcpy( ) Copies one string into another string string.h 23 strcmp( ) Compares two strings 24 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 radiansExample5.33:float x=0.5, angle=60, x1,x2,x3,a1,a2,a3;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 Recursion5.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(); Output --------} KLU KLUExample5.36: KLU KLUvoid main() …….{ ……. printf(“nKLU”); Infinite number of times main(); ( “KLU” is displayed infinite number} of times)5.7.2 How to write a recursive functionSince recursion process simulates repetitive process, it is required to check a condition for stopping orrepeating the process. A recursive function has two parts. i. Base part ii. Recursive partThe code written for stopping the repetitive process is the base part and the code written for repeatingthe same function call is called recursive partExample5.37: Recursive function to find factorial of an integerFactorial of an integer is a recursive function in Mathematics and is defined as followsn!= 1, if n=0 or 1 = n(n-1)! , if n>1Using 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:
    • Assume n = 5. Since the value of n is not 1, the statement f = n * factorial (n-1); n=0 Call-6 f= 1 will be executed with n = 5 that is f=1 f = 5*factorial (4); n=1 will be evaluated. The expression on the right- Call-5 f=1 x 0! f=1 hand side includes a call to factorial with n = 4 this call will return the following value. n=2 Call-4 f=2 x 1! f=2 4*factorial (3) Once again, factorial is called with n = 3, 2, 1 n=3 and 0, when n = 0 the function returns 1. The Call-3 f=3 x 2! f=6 sequence of operations can be summarized as follows: n=4 Call-2 f=4 x 3! f=24 f = 5*factorial(4) = 5*4*factorial(3) n=5 = 5*4*3*factorial(2) Call-1 f=5 x 4! f=120 = 5*4*3*2*factorial(1) = 5*4*3*2*1*factorial(0) Stack = 5*4*3*2*1*1 = 120 Calling functionlong int factorial( int n );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 classes5.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 calledlocal variables, However, variables may be declared outside the scope of a function such variables arecalled 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: Outputmain() value of i inside the block = 100{ int i=4; value of i outside the block=5 int j=10; i++; if (j > 0) { int i=100; printf("value of i inside the block = %dn",i); } printf("value of I outside the block= %dn",i);}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 initialser int 0 char ‘0’ float 0 pointer 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 = %dn", i ); Output } Value of local variable in the function func i = 11 func() Value of global variable i = 5 { int i=10; /* Local declaration of i */
    • i++; printf( "Value of local variable in the function func i = %dn", i ); } Global variables Local variables Variables declared outside a function are called global variables.Variables declared inside a function are global variables Note: differences between local andcalled local variables. For example int x,y;For example void main( ) void main( ) { ……. { int x,y; ……. …….. } …….. } Global variable can be accessed throughout the programLocal variable can be accessed only withinthe function in which it is defined Global variables can be accessed by anyVariables defined in one function cannot be function which falls in their scope.accessed in other functions. Global variables can retain their valuesLocal variables do not retain their values though out the execution of the programonce the control has been transferred out ofthe defining function. Values of global variable can be modified by other functions which fall in its scope.Values of local variable cannot be modifiedby other functions except the function in x2:/without y word externwhich it is defined. ollowing program notIf the values of local variables are needed by accessed i ables areother functions they must be passed through destroied.arguments in the function call 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
    • 5.8.2 Storage ClassesEach 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 data float 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. • 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 Storage_class data_type variable_name1, variable_name2,…..; For example auto int x; // x is an automatic integer variable static float y // y is static floating point variable5.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 forexecution and is destroyed when the control is exited from its defining function void main( ) { int i; for(i=1; i<5; i++) printf(“%dn”, fun1( )); } Output int fun1( ) x=11 { x=10; x=11 return(++x); x=11 } x=11 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 void main( ) { int y; Output printf(“n y=%d”, y+=5); } y= garbage 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); } x- is local to main( ) but void fun1() not accessed in fun1( ) { int y=50; Printf(“n x=%d”,x);
    • Printf(“n y=%d”, y); } void fun2() x- is local to main( ) and { x=1000; y- is local to fun1( ) but Y=2000; not accessed in fun2( ) } • 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? int x = 100; Scope of x global main() { int a; Scope of a printf(“n x=%d”,x); if(x>=100) Scope of x { The global int x = 10; variable x=100 Output is not accessed printf(“n x=%d”,x); here because } of scope of x=100 local variable x=10 x=10 Printf(“n x=%d”, x); x=100 }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. 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)’ Output fun1(); fun2(); x=96 printf(“n x=%d”,x); x=200 } x=200 void fun1( ) x=500 { 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( ) External variable { extern int X; declaration (memory printf(“n X=%d”, X ); not allocated) fun1(); } External variable int X; definition (memory void fun1() is allocated) { X=200; frintf(‘n X=%d”, X ); } Output X=200 X=200Declaration 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 external int s; // s is external void 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 ……….. } • 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 void main( ) { int i; for(i=1; i<5; i++) printf(“%dn”, fun1( )); } Output int fun1( ) x=11 { static x=10; x=12 return(++x); x=13 } x=14
    • 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 static int x; void main( ) { static int y; Output printf(“n x=%d”, ++x); printf(“n y=%d”, y+=5); x=1 } y=5 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. • 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 CPU5.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 functions name are required. You can pass one or more parameters to a function as follows: 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 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 dont 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.10Review 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? 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 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 numbers10. Write a program to reverse a integer using a recursive function11. 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 sequence12. 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 function13. 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 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:2Write a function to return GCD of two numbers and call this function in main to find GCD and LCM offour 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; } } while(r!=0);}Program:3Write 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 withone-dimensional array as formal parameter.To pass one-dimensional array to a called function, simply refer the name of array as actual argumentwithout any subscripts, and size of array.Program:4Write a function to return largest of a list of integers and call this function in main to find largest of agiven 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]); 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(“nnElements before sort:nn”); for(i=0;i<n;i++) printf(“%5d”,rank[i]); sort(rank,n); printf(“nn Elements after sort:nn”); 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]) { 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 onthe 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(){ 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 usingfunctions.#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”);}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++) 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 ormulti-dimensional char variablePassing one-dimensional char variable to a called function:To pass one-dimensional char variable as actual argument simply refer its array name but in functiondefinition 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 isn”); 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 functiondefinition 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(){ 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 isn”); 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]);}