Unit 5 - Functions
Unit 5 - Functions
Unit 5 - Functions
Unit 5
UNIT- 5 FUNCTIONS
UNIT STRUCTURE 5.1 Learning Objectives 5.2 Introduction 5.3 Usefulness of Function 5.4 General Forms of Function 5.4.1 Function Prototype 5.4.2 Function Definition 5.4.3 Function Call 5.5 Function Parameters 5.5.1 Passing Arguments to a Function 5.6 Nesting of Functions 5.7 Categories of Function 5.8 Recursive Function 5.9 Let Us Sum Up 5.10 Further Readings 5.11 Answers To Check Your Progress 5.12 Model Questions
5.2 INTRODUCTION
A number of segments grouped into a single logical unit is referred to as function. A function is a set of program statements that carries out some specific task and can be processed independently. In our earlier units while writing programs, we have already used functions like scanf( ), printf( ), clrscr( ), sqrt( ) etc. We have seen that C supports the use of such library (or built-in) functions, which are used to carry out a number of commonly used operations or calculations.
Functions
Unit 5
However, C also allows the users to define their own functions for carrying out various individual tasks of programming. This unit concentrates on the creation and utilization of such user-defined functions. With the proper use of such user-defined functions, a large program can be broken down into a number of smaller, self-contained components, each of which has some unique purpose.
Functions
Unit 5
Functions
Unit 5
Functions
Unit 5
header is followed by an opening { and a closing brace }. The statements within the opening and closing braces constitute the function body. Function name should be appropriate to the task performed by the function. In C, two function name should not be same in a single file. If the function does not return anything then the return type will be void otherwise, it is the type of the value returned by the function. If the return type is not mentioned explicitly, C compiler assumes that it is an integer type. Return statement contains the output produce by the function and its type. The return statement serves two purposes: On executing the return statement, it immediately transfers the control back to the calling program. It returns the value to the calling program. Example: Let us consider the following program segment int add(int a, int b) { int sum = 0; // local variable sum and it is intialised to zero sum = a + b; return sum; // value of sum is returned to the calling function } In the above program segment, the summation of the value stored in the variable a and b are returned. As the summation of two interger is also an integer, so the return type is int . Example: Let us consider the following program segment void display( ) { printf(State Open University ); } display( ) function does not return anything. So, the return type is void. We can also write the display( ) function as void display(void) by mentioning void explicitly within the bracket because no argument is passed.
Functions
Unit 5
In the above statement add(a,b) function is called and value returned by it is stored in the variable s. When the compiler encounters a function call, the control is transferred to int add(int x, int y ). This function is then executed line by line as described and a value is returned when a return statement is encountered. In our example, this value is assigned to s. This is illustrated below: Program2: Program to find the summation of two numbers using function #include<stdio.h> #include<conio.h> // function declaration int add(int, int); void main() { int a,b,s; clrscr(); printf(Enter two integer number \n); scanf(%d%d, &a,&b); s=add(a,b); // function call printf(\nThe summation is %d, s); getch(); } int add(int x, int y) //function header { int sum=0; // local variable sum and it is intialised to zero sum=x+y; return sum; // value stored in sum is returned to the calling function } Program3: Program to find the maximum of two numbers #include<stdio.h> #include<conio.h>
Functions
Unit 5
void main() { int max(int, int); int a,b, big; printf(\nEnter two numbers:); scanf(%d%d, &a,&b); big=max(a,b); printf(\nThe maximum of two numbers is: %d, big); getch(); } int max(int x, int y) { int large; if(x>y) large = x; else large = y; return large; } The above program will give the maximum of two integer numbers. The statement int max(int, int); is the declaration or prototype of the function. The function definition includes statements that test the two input argument numbers and returns the larger number. The variable a,b, big are local to the function main and the variable large is a local variable to the function max. The scope of the variable is local to the function, unless it is a global variable. For example, int function1(int i) { int j = 50; double function2(int j); function2(j); } double function2(int p) { double m; return m; }
Functions
Unit 5
The variable j in function1 is not known to function2. We pass it to function2 through the argument j. This will be assigned as equal to int p. In the same way, m in function2 is not known to function1. It can be made known to function1 through the return statement. This makes the scope rules of variables in function quite clear. The scope of variables is local to the function where defined. However, global variables are accessible by all the functions in the program if they are defined above all functions.
Formal Parameters
The parameters which appear in the first line of the function definition are referred to as formal parameter (commonly called parameters). Formal parameters are written in the function prototype and function header of the definition. Formal parameters are local variables which are assigned values from the arguments when the function is called.
Actual Parameters
When a function is called, the values (expressions) that are passed in the call are called the actual parameters (often known as arguments). At the time of the call each actual parameter is assigned to the corresponding formal parameter in the function definition. It may be expressed in constants, single variables, or more complex expressions. However, each actual parameter must be of the same data type as its corresponding formal parameter. The following rules apply to parameters of C functions: Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. Arguments are separated by commas. The scope of function parameters is the function itself. There-
Functions
Unit 5
fore, parameters of the same name in different functions are unrelated. Let us consider the following example to illustrate formal and actual parameters: Program4: #include<stdio.h> #include<conio.h> void display(int, int); void main() { int a,b; display(a,b); getch(); } void display(int x, int y) { printf(%d%d,x,y); } Here, x and y are formal parameters and take the value (a,b) from the calling function display(a,b).
Functions
Unit 5
void func(int, int); void main(void) //calling function { int x = 5, y = 10; clrscr(); func(x, y); printf(In main, x = %d y = %d\n, x, y); } void func(int a, int b) //called function { a = a + b; printf(In func, a = %d b = %d\n, a, b); } Output : In func, a = 15 b = 10 In main, x = 5 y = 10 In the above example, the calling function main() passes two values 5 and 10 to the called function func(). The function func() receive copies of these values and accesses them by the identifiers a and b. The function func() changes the value of a. When control passes back to main(), the actual values of x and y are not changed. Pass by reference Pass by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. For better understanding the concept of pass by value and pass by reference, let us consider the following two examples. In the example, our aim is to swap (interchange) two values. Program6: Example to illustrate calling a function by value. #include<stdio.h> #include<conio.h> void swap(int, int); //function prototype or declaration void main() { int a,b; a=5; b=10; printf(In main(), a and b before interchange: %d %d, a, b); swap(a,b); //function call printf(\nIn main(), a and b after interchange: %d %d, a, b);
10
Functions
Unit 5
getch(); } void swap(int i, int j) //function definition { int t; printf(\nWithin swap(), i and j before interchange: %d%d, i,j); t = i; i = j; j = t; printf(\nWithin swap(), i and j after interchange: %d%d, i,j); } Here, the values of a and b are passed through swap(a, b); When we execute this program, no interchange takes place within the main() function before and after calling swap(), although the interchange takes place within swap(). The output will be like this: In main(), a and b before interchange: 5 10 Within swap(), i and j before interchange: 5 10 Within swap(), i and j after interchange: 10 5 In main(), a and b afetr interchange: 5 10 To make this function work correctly we can use pointers, as shown below. Our next unit will help you in understanding pointers. So, instead of passing two integers to the swap() function, we can pass the addresses of the integers that we want to swap. Program7: Example to illustrate passing arguments by reference #include <stdio.h> #include<conio.h> void swap(int *, int *); //function declaration void main( ) { int a,b; a=5; b=10; clrscr( ); // clearing the screen printf(a and b before interchange: %d %d\n,a,b); swap(&a,&b); //function call, address of variable a and b are passed printf(a and b after interchange: %d %d\n,a,b); } void swap(int *i, int *j) {
11
Functions
Unit 5
int t; t = *i; *i = *j; *j = t; } Here, the arguments are passed by reference. To accomplish this, first, the function definition must be changed to accept the addresses of the two integers. This is done by specifying void swap(int *i, int *j) instead of swap(int i, int j) Inside the function, instead of using i, which now means the memory address of an integer, we have to access the value that is addressed by i. This is done by using *i and *j instead of i and j respectively. Secondly, the call in main() must be changed to pass the addresses of a and b instead of their values. This is done by calling swap(&a, &b); Addresses are passed by using the symbol & and the valuees are accessed by using the symbol *. When the function swap is called, addresses of a and b are passed. Thus, i points to a and j points to b. Once the pointers are initialized by the function call, *i is another name for a, and *j is another name for b. When the code uses *i and *j, it really means a and b. When the function swap() is called, the actual values of the variables a and b are exchanged because they are passed by reference. The output will be : a and b before interchange: 5 10 a and b after interchange: 10 5 Program8: Program to generate fibonacci numbers using iteration. #include<stdio.h> #include<conio.h> void main() { void Fibo(unsigned int n); //function prototype unsigned int n; printf(Program to generate fibonacci numbers: ); printf(\nEnter the total number to be generated:); scanf(%d,&n); Fibo(n); //function call, n is the argument to the function }
12
Functions
Unit 5
void Fibo(unsigned int num) { unsigned int p=1, q=0; unsigned int current; printf(\nFibonacci numbers:\n); printf(0\n); do { current=p+q; printf(\n%u\n, current); q=p; p=current; num - -; }while(num>1); //return; }
4 Fill in the blacks: (i) When a function returns nothing then the return type is_____. (ii) If a C program has only one function then that function is ________. (iii) The parameters used in a function call are______. (iv) When a variable is passed to a function by value, its value remains___________in the calling program. (v) A function can be called either by _______ or _______or both. 5. Write down the syntax of function definition. 6. Write the first line of the function definition, including the formal argument declarations, for each of the situations described below: (i) A function called average accepts two integer arguments and returns a floating-point result. (ii) A function called convert accepts a character and returns another character.
13
Functions
Unit 5
14
Functions
Unit 5
and prints the result. We have the following three functions: main( ) ratio( ) difference( ) main( ) reads the value of a,b,c and calls the function ratio( ) to calculate the value a / (b-c). This ratio cannot be evaluated if (b-c) =0. Therefore, ratio( ) calls another function difference( ) to test whether the difference(b-c) is zero or not.
a b -c
15
Functions
Unit 5
Functions with arguments and no return values Program11: #include<stdio.h> #include<conio.h> //function declaration with two argument void multi(int,int); void main( ) { int a,b; clrscr( ); printf(Enter two integers:); scanf(%d%d, &a,&b); multi(a,b); getch( ); } void multi(int a,int b ) { int m; m=a*b; printf(\nThe product is: %d,m); } Functions with arguments and one return value Program12: #include<stdio.h> #include<conio.h> //function declaration with two argument int multi(int,int); void main( ) { int a,b,m; clrscr( ); printf(Enter two integers:); scanf(%d%d, &a,&b); m=multi(a,b); printf(\nThe product is: %d,m); getch( ); } int multi(int a,int b ) { int z; z=a*b; return z; /*return statement. the value of z is returned to } the calling function*/
16
Functions
Unit 5
Functions with no arguments but a return value Program13: #include<stdio.h> #include<conio.h> int multi(void); //function declaration with no argument void main( ) { int m; clrscr( ); m=multi( ); printf(\nThe product is: %d,m); getch( ); } int multi(void) { int a,b,p; printf(Enter two integers:); scanf(%d%d, &a,&b); p=a*b; return p; } Return statement can return only one value. In C, the mechanism of sending back information through arguments is achieved by two operators known as the address operator (&) and indirection operator (*). Let us consider an example to illustrate this. Functions returning multiple values Program14: #include<iostream.h> #include<conio.h> void calculate(int, int, int *, int *); void main( ) { int a,b,s,d; clrscr( ); printf(\nEnter two integer:); scanf(%d%d,&a,&b); calculate(a,b,&s,&d); printf(\nSummation is:%d \n Difference is:%d, s,d); getch(); }
17
Functions
Unit 5
void calculate(int x,int y, int *sum, int *diff) { *sum=x+y; *diff=x-y; } In the fuction call, while we pass the actual values of a and b to the function calculate(), we pass the address of locations where the values of s and d are stored in the memory. When the function is called, the value of a and b are assigned to x and y respectively and address of s and d are assigned to sum and diff respectively. The variables *sum and *diff are known as pointers and sum and diff as pointer variables. Since they are declared as int, they can point to locations of int type data.
18
Functions
Unit 5
The factorial of a number can also be determined using recursion. The factorial of a number n is expressed as a series of repeatitive multiplications as shown below: Factorial of n = n(n-1)(n-2)(n-3).....1 For example, Factorial of 5= 5*4*3*2*1 =120 Program16: Factorial of an integer number #include<stdio.h> #include<conio.h> long int factorial(int); void main( ) { int n ; long int f ; clrscr( ) ; printf("\nEnter an integer number:") ; scanf("%d", &n) ; f=factorial(n) ; printf("\nThe factorial of %d is : %ld",n,f) ; getch() ; } long int factorial(int n) { long int fact ; if(n<=1) return(1); else fact=n*factorial(n-1); return(fact); } Let us see how recursion works assuming n = 5. If we assume n=1 then the factorial( ) function will return 1 to the calling function. Since n 1 , the statement fact = n * factorial (n-1); will be executed with n=5. That is, fact = 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) In this way factorial(3), factorial(2), factorial(1) will be returned. The sequence of operations can be summarized as follows:
19
Functions
Unit 5
fact = 5 * factorial (4) = 5 * 4 * factorial (3) = 5 * 4 * 3 * factorial (2) = 5 * 4 * 3 * 2 * factorial (1) =5*4*3*2*1 =120 When we write recursive functions, we must have an if statement somewhere to force the function to return without the recursive call being executed. Otherwise, the function will never return. Program17: Find the sum of digits of a number using recursion. #include<stdio.h> #include<conio.h> void main() { int sum(int); //function prototype int n,s; clrscr(); printf(\nenter a positive integer:); scanf(%d,&n); s=sum(n); printf(\nSum of digits of %d is %d , n,s); getch(); } int sum(int n) { if(n<=9) return(n); else return(n%10+sum(n/10)); // recursive call of sum() } Output : Enter a positive integer: 125 Sum of digits of 125 is 8 Recursion is used for repetitive computations in which each action is stated in terms of a previous result.
20
Functions
Unit 5
EXERCISE
Q. Write a C program to find the GCD (Greatest Common Divi sor) of two positive integers using recursion. Q. Write a C program to read in three number and print their maximum and minimum with the help of function. Q. Write a C program to find the sum of the squares of the even numbers between 1 and 20. Q. Write a function which returns the area of a triangle when the base and height are given to it as parameters. The function should have proper checking to ensure that both base and height are positive numbers. If not, it is to print an error message and return the area as zero. Write a complete C program to use this function.
7. State whether the following statements are true(T) or false(F) (i) The parameters which appear in the first line of the function definition are formal parameter (ii) Arguments are separated by semicolon. (iii) The C language does not support recursion. (iv) The main( ) function can call itself recursively. (v) You can call main() from any other function. (vi) The same variable names can be used in different functions without any conflict. 8. Write a C program to generate first n Fibonacci terms using recursion.
21
Functions
Unit 5
1. Balagurusamy, E: Programming in ANSI C, Tata McGraw-Hill publication. 2. Gottfried Byron S: Programming with C, Tata McGraw-Hill publication.
22
Functions
Unit 5
1. (i) True
(ii) False
(iii) True
2. void calculate(float, float); 3. The statement int multiply(int, int); is a function declaration where the function name is multiply which has two integer type arguments and its return type is integer. 4. (i) void (ii) main( ) (iii) actual parameters (iv) unchanged (v) call by value, call by reference 5. General format of function definition is given below : return_type function_name(parameter list) { local variable declaration; executable statement1 ; executable statement2 ; ................. ................. return statement ; } 6. (i) float average(int a, int b) (ii) char convert(char a) 7. (i) True, (ii)False, (iii) False, (iv) True (v) False (vi) True 8.Solution: #include<stdio.h> #include<conio.h> void main() { unsigned long fibo(int); int i,n;
23
Functions
Unit 5
clrscr(); printf(\nHow many fibonacci terms do you want ?\n); scanf(%d,&n); printf(\n%d fibonacci terms are: \n\n,n); for(i=1;i<=n;i++) printf(%4lu,fibo(i)); //function call getch(); } unsigned long fibo(int n) { if(n==1) return(0); else { if(n==2) return(1); else return(fibo(n-1)+fibo(n-2)); } }
//recusive call
24
Functions
Unit 5
5. What is the purpose of return statement? 6. Can a function be called from more than one place within a program? 7. What is recursion? Explain it with example. 8. Write a complete C program that will calculate the real roots of the quadratic equation ax2+bx+c=0. 9. Write a C program using function to find the square of an integer number without using the library function sqrt( ). 10. What is the purpose of the keyword void? Where is this keyword used?
*****
25