FUNCTIONS
FUNCTIONS
UNIT III-FUNCTIONS AND POINTERS After the called function is executed, the control is
returned back to the calling function.
Introduction to functions: Function prototype, function definition,
function call, Built-in functions (string functions, math functions) – Why functions are needed?
Recursion – Example Program: Computation of Sine series,
Scientific calculator using built-in functions, Binary Search using
recursive functions
3.1 FUNCTIONS
1
CS8251- PROGRAMMING IN C
Placing the function declaration statement prior to its
header file, enables the compiler to make a check on the
arguments used while calling that function.
The general format for declaring a function that accepts some
arguments and returns some value as a result can be given as:
2
CS8251- PROGRAMMING IN C
Swaps or interchanges
Return data type Converts a character to void swap(inta, int the value of integer
uppercase. The function b); variables aand b received
char convert_to_ receives a character as an as arguments. The
uppercase (char ch); argument, converts it into function returns no value,
upper case and returns therefore the return type
the converted character is void
back to the calling
function. The function is used to
void print(void); print information on
Calculates average of screen. The function
two integer numbers a neither accepts any value
Function name
and b received as as argument nor returns
float avg (int a, int arguments. The function any value. Therefore the
b); returns a floating point return type is void and
value. the argument list contains
void data type
int find_largest(int Finds the largest of three
a, int b, int c); nos a ,b and c arguments.
An integer value which is A function having void as its return type cannot return any
Data type of the largest of the 3 nos is value.
variable returned to the calling fn. A function having void as its parameter list cannot accept
any value. So the function declared as
Double multiply Multiplies two floating void print(void) ;
(float a, float b); point numbers a and b or
Variable 1 That are received as void print();
arguments and returns a does not accept any input/arguments from the calling function.
double value. If the function declaration does not specify any return
type, then by default, the function returns an integer
value. Therefore when a function is declared as
int sum(int a, int b);
3
CS8251- PROGRAMMING IN C
3.1.2 Function Definition 3.1.3 Function call
When a function is defined, space is allocated for that function The function call statement invokes the function.
in the memory. When a function is invoked the compiler jumps to the called
A function definition comprises two parts: function to execute the statements that are part of that function.
- Function header Once the called function is executed, the program control passes
- Function body back to the calling function.
The syntax of a function definition can be given as: Function call statement has the following syntax:
return data_type function_name(data_type variable1, function_name (variablel, variable2, ... );
data_type variable2,….) When the function declaration is present before the function
{ call, the compiler can check if the correct number and type of
………….. arguments are used in the function call and the returned value, if
statements any, is being used reasonably.
…………. Function name and the number and type of arguments in the
return(variable); function call must be same as that given in the function
} declaration and function header of the function definition.
The number of arguments and the order of arguments in the If the parameters passed to a function are more than what it is
function header must be same as that given in the function specified to accept then then the extra arguments will be
declaration statement. discarded.
While return data_type function_name(data_type variablel, If the parameters passed to a function are less than what it is
data_typevariable2, .. ) is known as the function header, the rest specified to accept then the unmatched arguments will be
of the portion comprising of program statements within { } is the initialized to some garbage value.
function body which contains the code to perform the specific task. Names (and not the types) of variables in function declaration,
The function header is same as function declaration. function call, and header of function definition may vary.
The only difference between the two is that a function header is not If the data type of the argument passed does not match with that
followed by a semicolon. specified inthe function declaration then either the unmatched
The list of variables in the function header is known as the formal argument will be initialized to some garbage value or a compile
parameter list. The parameter list may have zero or more time error will be generated.
parameters of any data type. Arguments may be passed in the form of expressions to the
The function body contains instructions to perform the desired called function.
computation in a function. In such cases, arguments are first evaluated and converted to
The argument names in the function declaration and function the type of formal parameter and then the body of the
definition need not be the same. function gets executed.
However, the data types of the arguments specified in function The parameter list must be separated with commas.
declaration must match with that given in function definition.
4
CS8251- PROGRAMMING IN C
If the return type of the function is not void, then the value 3.1.4 Return statement
returned by the called function may be assigned to some
variable as shown in the following statement. The return statement is used to terminate the execution of a
variable_name = function_name(variablel, variable2, ...); function and returns control to the calling function.
The control passes from the called function to the calling
Eg: Add two integers using functions. function when the return statement is encountered.
A return statement may or may not return a value to the calling
#include <stdio.h> function.
int sum(int a, int b); The syntax of return statement can be given as
int main() return<expression>;
{ Here expression is placed in between angular brackets because
intnuml, num2, total = 0; specifying an expression is optional.
printf("\n Enter the first number:”) The value of expression, if present, is returned to the calling
scanf ("%d", &numl); function.
printf("\n Enter the second number: “); However, in case expression is omitted, return value of the
scanf ("%d", &num2); function is undefined.
total = sum(numl, num2); Functions that have no return statement, the control automatically
printf ("\n Total = %d", total); returns to the calling function after the last statement of the called
return 0; function is executed.
} The return statement, like the break statement, is used to cause a
premature termination of the function.
int sum(int a, int b)
{ A function have more than one return statement
int result;
result = a + b; #include <stdio.h>
return result; #include <conio.h>
} int check_relation(int a, int b);
Output int main()
{
Enter the first number: 20 int a=3, b=5, res;
Enter the second number: 30 clrscr () ;
Total = 50 res = check_relation (a, b);
if(res==0)
printf("\n EQUAL");
if(res==l)
5
CS8251- PROGRAMMING IN C
printf("\n a is greater than b"); If the called function is supposed to modify the value of the
if(res==-l) parameters passed to it, then the change will be reflected only in
printf("\n a is less than b"); the called function.
getch(); In the calling function no change will be made to the value of
return 0; the variables. This is because all the changes were made to the
} copy of the variables and not to the actual variables.
3.2.1 Call by Value 3.2.1 Eg:// Call by value with return statement
In the call by-value method, the called function creates new #include <stdio.h>
variables to store the value of the arguments passed to it. int add (int n);
Therefore, the called function uses a copy of the actual int main()
arguments to perform its intended task. {
6
CS8251- PROGRAMMING IN C
int num = 2; - So although the called function may modify the value of the
printf ("\n The value of num calling the function = %d”, num); variables, these variables remain unchanged in the calling
num= add (num); function.
printf ("\n The value of num after calling the function = %d", nurn);
return 0; Eg: Call by Reference
}
int add(int n) #include <stdio.h>
{ void add (int *n);
n = n + 10; int main ()
printf ("\n The value of num in the called function = %d", n) ; {
return n; int num = 2;
} printf("\n The value of num before calling the function = %d",num);
Output: add (&num);
The valueof number before calling the function = 2 printf("\n The value of num after calling the function = %d", num) ;
The value of numin the called function = 12 return 0;
The valueof numafter calling the function = 12 }
void add(int *n)
While passing arguments toa function using the call-by-value {
method: *n = *n + 10;
When arguments are passed by value, the called function printf("\n The value of num in the calledfunction = %d", *n) ;
creates new variables of the same data type as arguments }
passed to it.
The values of the arguments passed by the function are copied Output
into the newly created variables. The value of numbefore calling the function = 2
Arguments are called by value when the called function does not The value of num in the called function = 12
need to modify the values of the original in the calling function. The value of num after calling the function = 12
Values of the variables in the calling function remain unaffected
when the arguments are passed using call by value technique. When the calling function passes arguments to the
call-by-value method of passing arguments mustbe used only in calledfunction using call-by-value method, the only way
two cases: toreturn the modified value of the argument to the caller is
- The called function does not need to modify the value of the actual explicitly using the return statement.
parameter. The better option when a function wants to modify the value of
- It simply uses the value of to perform its task. the argument is to pass arguments using call-by-reference
- The called function should only temporarily modify the value of technique.
the variables and not permanently. In call by reference, we declare the function parameters
as references rather than normal variables.
7
CS8251- PROGRAMMING IN C
When this is done any changes made by the function to the swap(x, y);
arguments it receives are visible in the calling function printf("After Swapping\nx = %d\ny = %d\n", x, y);
To indicate that an argument is passed using call by reference, return 0;
an asterisk (*) is placed after the type in the parameter list. }
This way, changes made to the parameter in the called function void swap(int a, int b)
will then be reflected in the calling function. {
Hence, in call-by-reference method, a function receives an implicit int temp;
reference to the argument, rather than a copy of its value. temp = b;
Therefore, the function can modify the value of the variable and b = a;
that change will be reflected in the calling function as well. a = temp;
printf("Values of a and b is %d %d\n",a,b);
Advantages }
Since arguments are not copied into new variables, itprovides Eg: Swapping of two values by call by reference
greater time and space efficiency.
The called function can change the value of the argumentand the #include <stdio.h>
change is reflected in the calling function. void swap(int*, int*);
A return statement can return only one value. In casewe need to int main()
return multiple values, pass those argumentsby reference. {
int x, y;
Disadvantages printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
The side-effect of using this technique is that when an argument is printf("Before Swapping\nx = %d\ny = %d\n", x, y);
passed using call by address, it becomes difficult to tell whether swap(&x, &y);
that argument is meant for input, output, or both. printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
Eg: Swapping of two values by call by value }
void swap(int *a, int *b)
#include <stdio.h> {
void swap(int, int); int temp;
int main() temp = *b;
{ *b = *a;
int x, y; *a = temp;
printf("Enter the value of x and y\n"); }
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
8
CS8251- PROGRAMMING IN C
Program on function to swap the value of two variables( call by
value & by reference) Output:
In main(), a = 1 and b = 2
#include <stdio.h> In function(Call By Value Method) a=2 and b= 1
void swap_call_by_val(int, int); In main(), a = 1 and b = 2
void swap_call_by_ref(int *, int *); In main(), c = 3 and d = 4
In function(Call By Reference Method) c=4 and d = 3
int main() In main(), c = 4 and d = 3
{
int a=l, b=2, c=3, d=4;
printf("\n In main 0 , a = %d and b %d",a, b); Eg: Greatest of 3 nos by using functions
swap_call_by_val(a, b); #include<stdio.h>
printf ("\n In main( ), a = %d and b = %d",a, b); int greater(int a, int b, int c);
printf ("\n In main (),c = %d and d =%d", c , d) int main()
swap_call_by_ref (&c, &d) ; {
printf("\n In main() , c = %d and d =%d", c , d); intnuml, num2, num3, large;
return 0; printf("\n Enter the first number :”);
} scanf("%d", &numl);
void swap_call_by_val(int a, int b) printf ("\n Enter the second number :”);
{ scanf ("%d", &num2);
int temp; printf("\n Enter the third number :”);
temp = a; scanf ("%d", &num3);
a = b; large = greater(numl, num2,num3);
b = temp; printf("\n Largest number = %d”,large);
printf("\n In function (Call By ValueMethod) a = %d and b = %d", return 0;
a, b); }
} int greater(int a, int b, int c)
void swap_call_by_ref(int*c, int*d) {
{ if(a>b && a>c)
int temp; return a;
temp = *c; if (b>a && b>c)
*c = *d; return b;
*d = temp; else
printf("\n In function (Call By ReferenceMethod) c = %d and d = return c;
%d",*c,*d); }
}
9
CS8251- PROGRAMMING IN C
Output: printf("\nEnter size of an array: ");
scanf("%d", &n);
Enter the first number : 45 printf("\nEnter elements of an array:\n");
Enter the second number: 23 for(i=0; i<n; i++)
Enter the third number: 34 scanf("%d", &a[i]);
Largest number = 45 selection_sort();
printf("\n\nAfter sorting:\n");
Eg: area of a circle using functions for(i=0; i<n; i++)
#include<stdio.h> printf("\n%d", a[i]);
float cal_area(float r); getch();
int main () }
{ void selection_sort()
float area, radius; {
printf ("\n Enter the radius of the circle: "); int i, j, min, temp;
scanf("%f", &radius); for (i=0; i<n; i++)
area = cal_area (radius) ; {
printf("\n Area of the circle with radius %f = %f", radius, area) ; min = i;
return 0; for (j=i+1; j<n; j++)
} {
float cal_area(float radius) if (a[j] < a[min])
{ min = j;
return (3.14 * radius * radius); }
} temp = a[i];
a[i] = a[min];
Output: a[min] = temp;
Enter the radius of the circle: 7 }
Area of the circle with radius 7=153.83 }
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i, n;
float x, sum, t;
clrscr();
16