Module3 Chapter2
Module3 Chapter2
Functions
3.12 Introduction
C enables its programmers to break up a program into segments commonly known as functions,
each of which can be written more or less independently of the others.
Every function in the program is supposed to perform a well-defined task.
Therefore, the program code of one function is completely insulated from the other functions.
Definition
“The set of instructions that performs some specific, well-defined task is called as a Function.”
Or
“Function is a small program or program segment that carryout some specific well-defined
tasks”.
Fig. 1.9 explains how the main() function calls another function to perform a well-defined task.
In the figure, we can see that main() calls a function named func1(). Therefore, main() is known as the
calling function and func1() is known as the called function.
The moment the compiler encounters a function call, the control jumps to the statements that are a
part of the called function.
After the called function is executed, the control is returned to the calling program.
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 1
Like C libraries, programmers can also write their own functions and use them from different
points in the main program or any other program that needs its functionalities.
When a big program is broken into comparatively smaller functions, then different programmers
working on that project can divide the workload by writing different functions.
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 2
3.15.1 Function Declaration/Function Prototype
Before using a function, the compiler must know the number of parameters and the type of
parameters that the function expects to receive and the data type of value that it will return to the
calling program.
Placing the function declaration statement prior to its use enables the compiler to make a check on
the arguments used while calling that function.
The general format for declaring a function that accepts arguments and returns a value as result can be
given as:
return_data_type function_name(data_type variable1, data_type variable2,..);
Here, function_name is a valid name for the function. A function should have a meaningful name that
must specify the task that the function will perform.
return_data_type specifies the data type of the value that will be returned to the calling function as a
result of the processing performed by the called function.
(data_type variable1, data_type variable2, ...) is a list of variables of specified data types. These
variables are passed from the calling function to the called function. They are also known as arguments
or parameters that the called function accepts to perform its task.
Ex: int add(int a,int b);
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 3
The syntax of a function definition can be given as:
return_data_type function_name(data_type variable1, data_type variable2,..)
{
.............
statements
.............
return(variable);
}
The number of arguments and the order of arguments in the function header must be the same as
that given in the function declaration statement.
While return_data_type function_name(data_type variable1, data_type variable2,...) is known as
the function header, the rest of the portion comprising of program statements within the curly
brackets { } is the function body which contains the code to perform the specific task.
Note that the function header is same as the function declaration. The only difference between the two
is that a function header is not followed by a semi-colon.
Ex: int add(int a,int b)
{
int sum;
sum=a+b;
return sum;
}
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 4
3.16 return STATEMENT
The return statement terminates the execution of the called function and returns control to the
calling function.
When the return statement is encountered, the program execution resumes in the calling function at
the point immediately following the function call.
A return statement may or may not return a value to the calling function.
The syntax of return state can be given as
return <expression>;
Here expression is placed in between angular brackets because specifying an expression is
optional.
A function that has void return type cannot return any value to the calling function.
1. Call by Value
In this method, the called function creates new variables to store the value of the arguments
passed to it. Therefore, the called function uses a copy of the actual arguments to perform its
intended task.
If the called function is supposed to modify the value of the parameters passed to it, then the
change will be reflected only in the called function. In the calling function, no change will be
made to the value of the variables. This is because all the changes are made to the copy of the
variables and not to the actual variables.
void main()
{
int a,b, res;
printf(“Enter the values of a and b:”);
scanf(“%d%d”,&a,&b);
res = add(a,b);
printf(“result =%d\n”, res);
}
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 5
Following are the points to remember while passing arguments to a function using the call-by value
method:
When arguments are passed by value, the called function creates new variables of the same
data type as the arguments passed to it.
The values of the arguments passed by the calling function are copied into the newly created
variables.
Values of the variables in the calling functions remain unaffected when the arguments are
passed using the call-by-value technique.
2. Call by Reference
When the calling function passes arguments to the called function using the call-by-value
method, the only way to return the modified value of the argument to the caller is explicitly
using the return statement. A better option is to pass arguments using the call-by-reference
technique.
In this method, we declare the function parameters as references rather than normal variables.
When this is done, any changes made by the function to the arguments it received are also
visible in the calling function.
To indicate that an argument is passed using call by reference, an asterisk (*) is placed after the type
in the parameter list. Hence, in the call-by-reference method, a function receives an implicit
reference to the argument, rather than a copy of its value. Therefore, the function can modify the
value of the variable and that change will be reflected in the calling function as well.
Example:
1. Write a C program to add two numbers using call by reference.
#include<stdio.h>
void main()
{
Output:
int a,b, res;
printf(“Enter the values of a and b:”); Enter the values of a and b: 4 5
scanf(“%d%d”,&a,&b); result =9
res = add(&a,&b);
printf(“result =%d\n”, res);
}
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 6
2. Write a C program to swap two numbers using call by reference.
#include<stdio.h>
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int a,b, res;
printf(“Enter the values of a and b:”); Enter the values of a and b: 10 20
scanf(“%d%d”,&a,&b); Before swapping: a=10 b=20
printf(“Before swapping: a=%d\tb=%d”, a, b); After swapping: a=20 b=10
swap(&a,&b);
printf(“After swapping: a=%d\tb=%d”, a, b)
}
Output:
Enter the values of a and b: 10 20
Before swapping: a=10 b=20
After swapping: a=20 b=10
Advantages
Since arguments are not copied into the new variables, it provides greater time and space efficiency.
The function can change the value of the argument and the change is reflected in the calling
function.
A function can return only one value. In case we need to return multiple values, we can pass those
arguments by reference, so that the modified values are visible in the calling function.
Disadvantages
However, the drawback of using this technique is that if inadvertent changes are caused to variables
in called function then these changes would be reflected in calling function as original values
would have been overwritten.
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 7
3.18.1 Block Scope
We have studied that a statement block is a group of statements enclosed within opening and
closing curly brackets { }.
If a variable is declared within a statement block then as soon as the control exits that block, the
variable will cease to exist.
Such a variable also known as a local variable is said to have a block scope.
So far we had been using local variables.
For example, if we declare an integer x inside a function, then that variable is unknown to the rest of
the program (i.e., outside that function).
Variables declared with same names as those in outer block mask the outer block variables while
executing the inner block.
In nested blocks, variables declared outside the inner blocks are accessible to the nested blocks,
provided these variables are not re-declared within the inner block.
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 8
Lifetime: Global variables are created at the beginning of program execution and remain in existence
throughout the period of execution of the program. These variables are known to all the functions in
the program and are accessible to them for usage. Global variables are not limited to a particular function
so they exist even when a function calls another function. These variables retain their value so that they
can be used from every function in the program.
Place of Declaration: The Global variables are declared outside all the functions including main(). It
is always recommended to declare them on top of the program code.
Name conflict: If we have a variable declared in a function that has same name as that of the global
variable, then the function will use the local variable declared within it and ignore the global variable.
Consider the following program,
#include <stdio.h >
int x = 10;
void print();
void main()
{
printf(“\n The value of x in the main() = %d”, x);
int x = 2;
printf(“\n The value of local variable x in the main() = %d", x);
print();
}
void print()
{
printf(“\n The value of x in the print() = %d”, x);
}
Output:
The value of x in the main() = 10
The value of local variable x in the main()= 2
The value of x in the print () = 10
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 9
It specifies how long the storage allocation will continue to exist for that function or variable.
It specifies the scope of the variable or function.
It specifies whether the variable or function has internal, external, or no linkage.
It specifies whether the variable will be automatically initialized to zero or to any
indeterminate value.
C supports four storage classes: automatic, register, external, and static.
The general syntax for specifying the storage class of a variable can be given as:
<storage_class_specifier> <data type > <variable name>
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 10
External variables may be declared outside any function source code file as any other variable is
declared.
Usually external variables are declared and defined in the beginning of a source file.
Memory is allocated for the external variables when the program begins execution and remains
allocated until the program terminates.
In case if the external variable is not initialized, then it will be initialized to zero by default.
External variables have global scope, i.e. these variables are visible and accessible from all the
functions in the program.
3.20 Recursion
“The process in which a function calls itself again and again is called as Recursion”.
A recursive function is defined as a function that calls itself to solve a smaller version of its task
until a final call is made which does not require a call to itself.
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 11
Since a recursive function repeatedly calls itself, it makes use of the system stack to temporarily store
the return address and local variables of the calling function. Every recursive solution has two major
cases. They are:
Base case, in which the problem is simple enough to be solved directly without making any
further calls to the same function.
Recursive case, in which first the problem at hand is divided into simpler sub-parts. Second the
function calls itself but with sub-parts of the problem obtained in the first step. Third, the result is
obtained by combining the solutions of simpler sub-parts.
Ex: To calculate n!, we multiply the number with factorial of the number that is 1 less than that number.
In other words, n! = n × (n–1)!
Every recursive function must have a base case and a recursive case. For the factorial function,
Base case is when n = 1, because if n = 1, the result will be 1 as 1! = 1.
Recursive case of the factorial function will call itself but with a smaller value of n, this case can
be given as:
factorial(n) = n × factorial (n–1)
Example:
1. Write a C program to calculate factorial of a given number.
#include<stdio.h>
int factorial(int n)
{
if(n==1)
return 1;
else
return (n*fact(n-1));
}
Output:
void main()
{ Enter a number: 5
int n,fact; Factorial of given number =120
printf(“Enter a number:”);
scanf(“%d”,&n);
fact=factorial(n);
printf(“\nFactorial of given number=%d”,fact);
}
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 12
2. Write a C program to calculate the GCD of two numbers using recursive functions.
#include <stdio.h>
int GCD(int x, int y)
{
int rem;
rem = x%y;
if(rem==0)
return y;
else
return (GCD(y, rem));
}
void main()
{
Output:
int x, y, res;
printf("\n Enter the two numbers: "); Enter the two numbers: 8 12
scanf("%d %d", &x, &y); GCD = 4
res = GCD(x, y);
printf("\n GCD = %d", x, y, res);
}
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 13
void main()
{ Output:
int n, i, res; Enter a value for n:
printf(“Enter a value for n:”);
5
scanf(“%d”,&n);
printf(“ The Fibonacci series is: \n”); The Fibonacci series is:
for ( i =0; i < n ; i ++) 0
{ 1
res = fibonacci(i); 1
printf(“%d\n”, res); 2
} 3
}
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 14
void main()
{
int m,n,res;
printf(“Enter the values for m,n\n”);
scanf(“%d%d”,&m,&n);
res=add(m,n); // Actual parameters m,n
printf(“Sum=%d\n”,res);
}
Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 15
inprotected.com