Page 1 :
Prof. Sachin Lamkane, Function :-, One of the most important feature of the structured programming language like c is to break a large program into many small programs. After breaking it into many small programs, individual small program in it is known as function. Programs written using functions are easy to understand as well as easy to detect and correct errors from it., Defination :-, “Funtion is a self contained block of statements that performs repetitive task.”, ‘ C ’ Function can be classified into two categories namely., 1) Library Functions (Built in Functions) and, 2) User defined Functions., printf(), scanf(), clrscr(), sqrt(), strlen() etc are the library functions which are not require to written by user or programmers. Where as user defined functions are written by the users to perform a specific task. Main() is an example of user defined function but main() is a special functions because execution of every c starts from main()., Advantages of User defined function :-, Use of function reduce the repetitions in the code., Use of functions reduce the length of program., Use of function within program reduce complexity of program so it is easy to understand as well as debug., Use of function improves logical clearity of program., Need for user defined Function:-, When we write a large program using only main() function, it leads to a number of problems. The program may become too large and complex and as a result hard to debugging, testing and maintenance. If a program is divided into functions, then each function is independently coded and later combined into a single unit called program. These sub programs called ‘ Functions’ are easier to understand, test and debug., A multifunction programs :-, We know that functions is self contained block of statement that performs a particular task. A large program is decomposed into several functions that independently perform a specific task., Fig :Multi Function Program, Example – Consider the following program to display output., * * * * * * * * * *, Hello everybody, * * * * * * * * * *, #include <stdio.h>, #include <conio.h>, Void printstar (void); /* Function declaration */, Void disply (void);, Void main(), {, Printstar ();, display ();, printstar ();, }, Void printstar (void), {, Inti ;, For (i=0; i<10; i++), Printf(“*”);, Printf(“\n”);, }, Void display (void), {, Printf(“Hello everybody \n”);, }, The above programs contains three user defined functions., Main( ) Function, Printstar( ) Function and, Display( ) Function, As we know, the program execution always begins with the main function. During execution of the main, the first statement encountered is, Printstar();, Which jumps to its definition and print ten star after that the control is transferred back to main then display () function is called its definition is executed and then control is transferred back to the main and again printstar () function is called and same definition is executed and again control transferred back to main and then program is terminated., Elements of user-defined Function :-, Following are the three elements of user defined function., 1) Function definition, 2) Function call, 3) Function declaration, Form of a C Function or Function definition :-, A general format of function definition is given below., Returntype functionname (Parameter list), {, Local variable declaration ;, Block of statements;, Return statement;, }, From above syntax, Function definition contains two parts, 1) Function header – The first line returntype Functionname (Parameter list) and, 2) Function body – Statements within opening and closing braces., Function Header :-, The function header consist of three parts, 1) returntype – That means which type of value is returned by the function to its, calling function i.e., int , float, void, 2) Functionname – Every function should have a specific name that adhere rules of identifiers., 3) Parameter list – The parameter are used to exchange information between the functions., Parameters used in function definition is known as formal parameters., Function Body :-, The function body contains the declarations and statements necessary for performing the required task. The function body contains three parts., 1) Local variable declaration needed by the function. A local variables is a variables that is defined inside the function., 2) Block of statements that perform the task of function, 3) A return statement that returns the value to its calling function. When a function reaches its return statement, the control is transferred back to the calling function. In the absence of a return statement, the closing brace act as a void return., Function call :-, A function can be called by simply using the function name followed by a list of actual parameters enclosed in parentheses., For example :-, Void main (), {, Int sum (int ,int); /* Function declaration */, Int result;, result = sum (5, 10); /* function call */, Printf (“sum = %d”, result);, getch();, }, Int sum (int x, int y) /* function definition */, {, Int t; /* local variable */, t = x + y ;, return (t);, }, Explanation :-, When the compiler encounters a function call sum(5,10), The control is tranfered to the function definition. The actual parameters 5 and 10 assigned to formal parameters x and y. then sum of x and y i.e, 5 and 10 is assigned to t and it is returned to its calling function., Important points related to function call :-, 1) If the actual parameters are more than the formal parameters, the extra actual parameters will be discarded,, 2) If the actual parameters are less than the formal parameters, the unmatched formal parameters will be initialized to some garbage value,, 3) Any mismatch in data type may also result in some garbage value., Function Declaration :-, Like a variable all functions in C program must be declared, before they are called. A function declaration is known as function prototype., Syntax :-, Returntype Functionname (Parameter list);, The above syntax consist of four parts:, 1) Return type is the type of value function returns. By default it is int., 2) Function name, 3) parameter list, 4) Terminating semicolon., A prototype declaration may be placed in two places in a program, 1) global prototype, 2) Local prototype, Return values and their types :-, A function may be send back any value to its calling function by using return statement. The return statement can take one of the following forms., Return;, Or, Return (expression);, The first return form does not return any value to its calling function., The second form of return with an expression returns the value of the expression, For examples the function, Int sum (int x, int y), {, Int t;, t = x + y;, return (t);, }, Returns the value of the t which is the sum of the values of x and y., The function can return different types of values like int , float, double etc. If the function does not return any value then returntype is specified as a void. By default returntype of function is int., Category of Functions:-, Depending on whether arguments are present or not and value is returned or not there are five different category of function., Category 1 : Function with no arguments and no return values., Category 2 : Function with arguments and no return values., Category 3 : Function with arguments and one return value., Category 4 : Function with arguments but return a value, Category 5 : Function that return multiple values., 1) Function with no arguments and no return value :-, When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not return a value, the calling function does not receive any data from the called function i.e, there is no data transfer between the calling function and the called function., Consider the example of printing * by using function, Void main(), {, Void pointstar(void);, Pointstar(); /* no argument */, getch();, }, Void printstar(), {, Inti;, For (i=0; i<20; i++);, Printf(“*”);, }, 2) Function with arguments but no return value :-, In this type of category of function, function is called with arguments i.e actual parameters and it is assigned to formal parameters in function definition but function in this category does not return any value i.e. return type of function is void., For example – Addition of two numbers, Sum(10,20); /*function call */, Void sum (int x, int y) /*function definition *, {, Printf(“Addition of two numbers= %d”, x+y);, }, 3) Function with arguments as well as return value :-, Consider the above sum() function as follows., Void main(), {, Intsum(int, int); /* Function declaration*/, Int result;, result = sum (10,20);, Printf(“sum= %d”, result);, getch();, }, Int sum(int x, int y), {, return (x + y), }, 4) Function with no arguments but return a value :-, These could be occasions where we may need to design functions that may not take any arguments but returns a value to the calling function, Consider the following example., Intget_number (void);, Void main (), {, Int m = get_number();, Printf(“m=%d”, m);, }, Int get_number(void), {, Int number;, Scanf(“%d”, &number);, return(number);, }, 5) Function that return multiple values :-, Up to now, we see functions that return just one value using return statement because, a return statement can return only one value. We can use pointer to return multiple values to its calling function., Example – Consider the following example that perform addition and substraction of two numbers., Void addsub(int x, int y, int *sum, int *sub), Void main (), {, int x=10, y=20, sum, sub;, addsub(x,y, &sum, &sub);, printf(“\n sum = %d \n sub= %d”, sum,sub);, }, Void addsub(int a, int b, int *s, int *d), {, *s = a + b;, *d + a – b;, }, Function with Array :-, As the values of fundamental data types are passed to the function as parameter, we can also pass the array as a parameter to the function. To pass a one dimensional array to a called function, it is necessary to pass array name without any the size of the array as arguments, Example – Consider the following program to find largest number from array by using function., void main (), {, int max (inta[], int n);, int value [5] = {10, 15, 50, 20, 22};, printf(“maximum = %d”, max(value, 5));, getch();, }, int max (int a[], int n), {, int I, max;, max = a[0];, For (i=1, i<n; i++), If (max< a[i]), max = a[i];, return(max);, }, Output :- maximum = 50, Rules to pass an array to a function :-, 1) The function must be called by passing only the name of the array., 2) In the function definition, the formal parameter must be an array type, the size of the array does not need to be specified., 3) The function prototype must show that the argument is an array., Recursion :-, Function calls itself is known as recursion. A function is called recursive if a statement within the body of a function calls the same function., First consider the non-recursive function for calculating the factorial of a number., Int factorial (int); /* prototype */, Void main(), {, Int no, fact;, Printf(“\n Enter any number ”);, Scanf(“%d”, &no);, Fact = factorial (no); /* function call */, Printf(“\n factorial = %d”, fact);, }, Int factorial (int x), {, Int f=1 , I;, For (i=x; i>=1; i--);, F=f*I;, Return(f);, }, Output :-, Enter any number : 5, Factorial : 120, Now, consider same program by using recursion., Int rec (int);, Void main (), {, Int no, fact;, Clrscr();, Printf(“\n Enter any nuber”);, Scanf(“%d”, &no);, Fact = rec (no); /* Function call */, Printf(“Factoral = %d”, fact);, getch();, }, Int rec (int x), {, Int f;, If (x==1), Return (1);, Else, f = x * rec (x-1); /* Function recursion */, Return (f);, }, Output :- Enter any number :- 5, Factorial :- 120, Storage classes in C :- (Scope, visibility and lifetime of variable), Storage classes of variable tell us :, 1) Where the variables would be stored., 2) What will be the initial value of the variable., 3) What is the scope the variable., 4) What is the lifetime of the variable., These are four storage class used in C, 1) Automatic storage class., 2) External storage class., 3) Static storage class., 4) Register storage class., 1) Automatic storage class :-, Automatic variables are declared inside a function in which they are to be utilized. They are created when function is called and destroyed automatically when the function is exited. Automatic variables are therefore private (or local) to the function in which they are declared., The features of automatic variables are as follows :, Storage – Memory, Default initial value – Garbage, Scope – Local, Lifetime – Till the control remains within the block in which the is , declared., For example :-, Void main (), {, int no;, Auto int sum ;, - - - - - - - -, - - - - - - - -, - - - - - - - -, }, A variable declared inside a function without storage class, is by default automatic. We may also use the keyword auto to declare automatic variables explicitly. So the storage class of both no and sum variables are automatic., 2) External storage class :-, Variables that are both arrive and active throughout the entire program are known as external variables. They are also known as global variables. Global variables can be accessed by any function in the program. External variables are declared outside a function., The features of external variables are as follows :, 1) Storage – Memory, 2) Default initial value – Zero, 3) Scope – Global, 4) Lifetime – Throughout the program., For example –, int number;, int sum;, Void main(), {, Statements;, }, Here number and sum are global variables., 3) Static Storage Classes :-, AS the name suggest the value of static variables persists until end of the program. A variable can be declared static using the keyword static., The features of static variables are as follows :, 1) storage - Memory, 2) Default initial value – Zero, 3) Scope – Local to the block in which the variable is defined., 4) lifetime – value of the variable persist between different function calles., Consider the following program which shows the difference between auto and static storage class., void increment(); void increment(), void main() void main(), { {, increment(); increment();, increment(); increment();, increment(); increment();, } }, Void increment() Void increment(), { {, Auto inti=1; static int I =1;, Printf(“%d”, i); print(“%d”, i);, i++; i++;, } }, Output :- 1 1 1 Output:- 1 2 3, 4) Register variables :-, These are in machines register, rather than memory where normal variables are stored. Since a register access is much faster than a memory access, so frequently accessed variables are stored in register will lead to faster execution of program. But the number of CPU register are limited and if it is not free then register variable is converted into auto., The features of register variables is as follows :, 1) storage - CPU Register, 2 ) Default initial value - Garbage., 3) Scope – Local to the block in which the block in which the variable is, defined., 4) Lifetime – Till the control remains within the block in which the variable is, define.