You are on page 1of 13
User defined functions and Recursion ‘A function is a block of code to perform a specific task. > Every C program has at least one function main ( ). Without main ( ) function, there is technically no C program. > In modular programming, the program is divided into separate small programs called modules. Each module is designed to perform specific function. Modules make our actual program shorter, hence easier to read and understand Advantages of functions: > Reusability: Particular set of instructions can be used repeatedly from several different places within the program. > Easy debugging: since each function is smaller and has a logical clarity, it is easy to locate and correct errors in it. > Build library: Functions allows a programmer to build a customized library of frequently used routines or system-dependent features. Each routine can be programmed as a separate function and stored within a special library file. ‘TYPES OF C FUNCTIONS: There are 2 types of functions in C programming: 1. Library function 2. User defined function Library Funetion Library functions are the in-built function in C compiler. For example: main( )//The execution of every C program starts from this main() function print{( ) //prinf() is used for displaying output in C sqrt(x)3// finds the square root of x scanf{ ) //scanf() is used for taking input in C User Defined Function C allows programmer to define their own function according to their requirement. These types of functions are known as user-defined functions. ADVANTAGES OF USER DEFINED FUNCTIONS: 1, User defined functions helps to decompose the large program into small segments which makes programmer easy to understand, maintain and debug. 2. If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function, Dept of CSE, Canara Engineering College. Page 105 3. Programmer working on large project can divide the workload by making different functions. FUNCTIONS AND PROGRAM STRUCTURE Basic structure of C program with function is shown below: #include //fanction global declarations; declaration or void function_name( parameter list); function prototype void main() { local declarations; statements; function_name (parameter list); // function call ) void function_name (parameter list) //function definition { local declarations; statements; ) v Every C program begins from main( ) and program starts executing the codes inside main( ) function. ‘When the control of program reaches to function_name( ) inside main( ) function, the control of program jumps to void function_name( ) and executes the codes inside it. > When all the codes inside that user-defined function are executed, control of the program jumps to the statement just after function_name( ) from where it is called, Vv Fun Every function in C program should be declared before they are used. Function declaration gives compiler information about > function name > type of arguments to be passed and > return type The syntax is shown below: return_type function_name formal parametres), m Declaration Function Call A function can be called by specifying its name followed by a list of arguments enclosed in the parentheses and separated by commas. ‘The syntax is shown below: function_name(actual parametres); Function Definition Function definition contains programming codes to perform specific task The syntax is shown below: return_type function_name formal parametres) f variable declarations; statementl; statement2; return value; Where return_type is the data type that the function returns. Function_name refers to the name of the function, The formal parameters are a comma separated list of variables that receive the values from the main program when a function is called, The return statement returns the result of the function, vvv v Return Type Function Name Local Declaration ol int sum ( inta, int b ) PaCSSCBRLISE (Formal Parameters: { intc; c=atb; return (c); } “Ss } Return Statement Statements sa my ACTUAL AND FORMAL parameters/ arguments. > Argument (or parameter) refers to data that is passed to function (function definition) while calling function, > Arguments listed in “function call” statements are referred to as actual arguments. These actual values are passed to a function to compute a value or to perform a task. > The arguments used in the “function declaration” are referred as formal arguments. They are simply formal variables that accept or receive the values supplied by the calling function. > ‘The number of actual and formal arguments and their data types should be same. Example: Program to add two integers. Make a function add integers and display sum in main() function. #include int add(int , int); // function prototype void main() ( int a,b, printf ("Enters two number to add \n"); scanf ("$d %d", &a, 6b); sum=add(a,b); //actual arguments printé("\n sum=8d", sum); int add(int a,int b) //formal arguments ( int sum; // local declaration sum=atb; return sum; Output : Enters two number to add 2 3 sum=5 ‘Actual Parameters Formal Parameters 1) Actual parameters are used in T) Formal parameters are used in the calling function when a function header of a called function function is invoked, 2) Actual parameters can be 2) Formal parameters should be only constants, variables or variables, expressions 3) Actual parameters send values 3) Formal parameters receive values to the formal parameters. from the actual parameters. a) Address of actual parameters 4) Ifformal parameters contains can be sent to formal address, they should be declared as parameters. pointers. Location of functions. Locations of functions suggest the placement of function definitions with respect to main() program. There are three alternative to specify the location for function Alternativel. In this type the function definition are placed before the main() program body. In this case defining or declaring function prototype can be omitted. Itis considered poor style to omit function prototype, even if it is not technically necessary. finclude and function prototvoe Function body ‘Main program Documentation Section: program to find the sum of two integers*/ #include /*link section*/ int addition( int x,int y) /* Function definition*/ { int s =x43 return s; /* Return statement to return the sum s*/ } void main) { int nt.n2sum ; “declaration part*/ printf("Enter the values of nl and n2\n"); executable part starts here*/ scanf{"*%éd %d” nl 802): sum = addition(n1 2); /* Function Call */ print{("Sum =%d \n * sum); Alternative? In this type the function definition are placed after the main( ) program. Here one has to place the function prototype statement well before main( ) program appearance in order to assists C compiler for type checking and function call location with respect to function definition. #include and function prototype Main program Function body /*Documentation Section: program to find the sum of two integers*/ #include /*link section*/ int addition( int. int ); "Function Prototype declaration section*/ void main() t int nin2sum; /*declaration part*/ print{("Enter the values of nl and n2\n"); executable part starts here*/ scanfi"%d %d!" &n1,&n2); stim = addition(n1.n2)./* Function Call */ printf("Sum =%d \n " sum): } int addition( int x,int y) /* Function definition*/ t int s: S=X+Y; return s; /* Return statement to return the sum s*/ } Alternative3 Here the function body is placed in one file and the main() program with function prototype in another file. In the file say add.h the following function will be defined Function body int addition( int x,int y) /* Function definition*/ a int s s= x4 returns; /* Return statement to return the sum s*/ I In the file say addition.c the following code has to be included #include /*link section*/ #include/* the header file which includes the function definition */ void main() t int n1.n2,sum /*declaration part*/ printf{"Enter the values of n1 and n2\n"); /*executable part starts here*/ scanf("%d %d",&n1 ,&n2); sum = addition(n1 ,n2); /* Function Call */ printf("Sum =%d \n sum); } ARRAYS AND FUNCTIONS The arrays can be passed to functions using two methods: 1. > > Passing Individual Elements of Array All array-elements can be passed as individual elements to a function like any other variable. The array-element is passed as a value parameter ie. any change in the formal- parameter will not affect the actual-parameter i.e. array-element. Example: Program to illustrate passing individual elements of an array to a function. #include void display (int a) { ) printf ("8d") a); void main() { int c{3]={2,3,4)7 display (c[2]); Output : 4 Passing the Whole Array > Here, the parameter passing is similar to pass by reference. > In pass by reference, the formal parameters are treated as aliases for actual parameters. > So, any changes in formal parameter imply there is a change in actual parameter. Example: Program to find average of 6 marks using pass by reference. #include void average(int m{]) { int i ,avg7 int avg, sum=0; for (i=0;1<6;i++) sum= sum+ m[i]; avg =(sum/6); printé ("aggregate marks= $d", avg); void main() ( int m[6]={60, 50, 70, 80, 40, 80, 70}; average(m); // here m is the base address. Output : aggregate marks= 70 CLASSIFICATION OF USER-DEFINED FUNCTIONS Function with no arguments and no return value ( void and parameter less functions) Function with no arguments and return value Function with arguments but no return value Function with arguments and return value Aepe 1, Funetion with no arguments and no return value (void and parameter less functions): > This type of functions will not have any parameter and they will not return any value to the calling functions. > There is no data transfer between the calling function and called function, So calling function cannot send values and hence called function cannot receive the data. Example: Program to illustrate function with no arguments and no return value. Hinclude void add(); void main() { add); , void add() ( int a, by sum; print£ ("Enters two number to add : "); scanf("$d $d", Ga, &b); sum=a+b; printé \n sum=$d", sum); Output : Enters two number to add : 23 sum=5 2.Funetion with no arguments and with return value : > In this category there is no data transfer from the calling function to the called function. But there is a data transfer from called function to the calling function. > When the function definition returns a value the calling function receives one value from the called function. Example: Program to illustrate function with no arguments and return value, Finclude int add(); void main() { int sum; sum=add(); peinté("\n sum-%d", sum); , int add() { int a, by sum; printf ("Enters two number to add \n"); scanf("$d $d", &a, &b); sum=atb; return sum Output : Enters two number to add 2 3 sum=5 3. Function with arguments but no return value : > Here there is a data transfer from the calling function to called function. > But there is no data transfer from the called function to the calling function, The called function will have parameters but no return type Example: Program to illustrate function with arguments but no return value include void add(int a, int b); void main() { int a, b, sum; printf("Enters two number to add \n"); scanf("%d %d", &a, &b); add(a, b); ) void add(int a, int b) ( sum= at b; printf ("\n sum a", sum); return; Output: Enters two number to add 2 3 sum=5 4, Function with arguments and return value : > In this category there is a data transfer between the calling function and called function. > When parameters are passed, the called function can receive values from the calling function, When the function returns a value the calling function can receive a value from the called function. Example: Program to illustrate function with arguments and return value #include int add(int a, int b); void main() { int a, b, sum; printf ("Enters two number to add \n"); scanf ("$d $d", &a, &b); sum=add (a,b) 7 peinté("\n sum=%d", sum); int add(int a, int b) { int sum sumatb; return sum; //return statement of function ) Output : Enters two number to add 2 3 sum=5 RECURSION > A function that calls itself is known as recut > The rule to be followed for recursive function is tat — Establish boundary conditions that terminate the recursive calls. > Implement the recursive calls so that each call brings one step closer to the solution. ve function, > Every recursive function must be provided with a way to end the recursion. In thi example when, n is equal to 0, there is no recursive call and recursion ends. Example: Program to find factorial of a number using recursion, #include t fact (int n) if (n==1) return 1; return (n*fact (n-1)); void main() ( int n,res; print£("Enter the value of n \n"); scan£("Sd", én); res=fact (n); printf ("result = %d",res); output: Enter a positive integer: Result = 120 The recursion refers to the process where a function calls itself either directly or indirectly. There are two types of recursion: 1 Direct recursion 2: Indirect recursion Direct Recursion: It refers to a process where function calls itself directly as illustrated in the figure below. Indirect recursion: It refers to a process where a function calls another function and that function calls back the original function. The process of indirect recursion takes place as illustrated below. Example: int fact( int n) { if (n==0) return 1; return(n*fact(n-1)); } Figure: direct recursion [> Funes. Figure: Indirect recursion Here the func1() calls fune2() and fune2() calls fune3() and fune3() calls fune1(). Example: Program to generate Fibonacci series using recursion #include int £ibonaeci (int); void main() ( int n, i= 0, 4; printé("\n Enter the number of terms : scanf("$d", &n); printf ("Fibonacci series terms are:\n"); for (c = 17 ¢ <= nj ct) ‘ uM print£("&d\t", fibonacei (i); itty int fibonacci(int n) ( if (n=O ll n return n; else return (fibonacci(n-1) + fibonacci(n-2))}

You might also like