Programming in C Reema Thareja
Programming in C Reema Thareja
Programming in C
Reema Thareja
CHAPTER 4
Functions
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
well -defined task. Theref
Therefore,
ore, the code of one
function is completely insulated from that of other functions.
• Every function has a name which acts as an interface to the outside world in terms of how information is
transferred to it and how results generated by the function are transmitted back from it.
• In the fig, main() calls another function, func1() to perform a well-defined task.
• main() is known as the calling function and func1() is known as the called function.
• When the compiler encounters a function call, instead of executing the next statement
statement in the calling
function, control jumps to the statements that are a part of the called function.
•
Introduction Contd.)
• It is not necessary that the main() can call only one function, it can call as many functions as it
wants and as many times as it wants. For example, a function call placed within a for loop,
while loop, or do-while loop may call the same function multiple times until the condition
holds true.
• It is not that only the main() can call another functions. Any function can call any other
function. In the figure, one function calls another, and the other function in turn calls some
other function.
} } } ……….
return;
}
Why Do We Need
Need Functions?
Functions?
• Dividing the program into separate well-defined functions facilitates each function to be written and
tested separately. This simplifies the process of getting the total program to work.
• Understanding,
Understanding, coding, and testing multiple separat
separate
e functions are far easier than doing the same for
one large function.
• If a big program has to be developed without the use of any function (excep
(exceptt main()), then there will be
countless lines in the main() function.
Terminology of Functions
• A function, f, that uses another function, g, is known as the calling function and g is known as the called
function.
•
When a called function returns some result back to the calling function, it is said to return that result.
• The calling function may or may not pass parameters to the called function. If the called function
parameters
accepts arguments, the calling function will pass parameter
parameters,
s, else not.
Function Declaration
Declaration
• Function declaratio
declarationn is a declaration statement that identifies a function with its name, a list of
arguments that it accepts, and the type of data it returns.
• The general format for declaring a function that accepts some arguments and returns some value as
result can be given as:
return_data_type
return_data_type function_name(data
function_name(data_type
_type variable1, data_type variable2,…);
Function Definition
Defin ition
Function definition consists of a function header that identifies the function, followed by the body of the
function containing the executable code for that function.
• When a function is defined, space is allocated for that function in the memory
memory..
………….
statements
………….
return( variable);
• The number and the order of arguments in the function header must be same as that given in function
declaration statement.
Function Call
• Function name and the number and type of arguments in the function call must be same as that given in
the function declaration and function header of the function definition.
• Names (and not the types) of variables in function declaration, function call, and header of function
• Arguments may be passed in the form of expressions to the called function. In such a case, arguments
are first evaluated and converted
converted to the type of formal parameter and then the body of the function
gets executed.
If the return type of the function is not void, then the value returned by the called function may be
assigned to some variable as given below:
#include<stdio.h>
in
intt ssum
um(i
(in
nt a
a,, in
int b)
b); // FUNC
FUNCTI
TION
ON DEC
DECLARA
LARATI
TION
ON
int main()
{
int num1, num2, total = 0;
printf(“\n Enter the first number : “);
scanf(“%d”, &num1);
printf(“\n Enter the second number : “);
scanf(“%d”, &num2);
total = sum(num1, num2); // FUNCTION CALL
printf(“\n Total = %d”, total);
return 0;
}
// FUNCTION DEFNITION
int sum ( int a, int b) // FUNCTION HEADER
{ // FUNCTION BODY
return (a + b);
}
© Oxford University Press 2018. All rights reserved.
Return Statement
• Programming Tip: It is an error to use a return statement in a function that has void as its return type.
A return statemen
statementt may or may not return a value to the calling function. The syntax of return statement
can be given as
return <expression> ;
• The value of expression, if present, is returned to the calling function. However, in case expression is
Call by value in which values of the variables are passed by the calling function to the called function.
Call by reference in which address of the variables are passed by the calling function to the called
function.
Call by Value
• In the Call by Value method, the called function creates new variables to store the value of the arguments passed
pass ed to it.
Therefore,
Therefore, the called function uses a copy of the actual arguments to perform its intended task.
Call by Reference
• When the calling function passes arguments to the called function using 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 when a function can modify the value of the argument is to pass arguments using Call by
Reference technique.
When this is done, any changes made by the function to the arguments it received are visible in the
calling function.
• To indicate that an argument is passed using call by reference, an asterisk symbol (*) is placed after the
#include<stdio.h>
void add( int *n);
int
int ma
main
in()
()
{
in
intt nu
num
m = 2;
printf("\n The value
value of num befor
before
e calling the function = %d", num);
add(num);
printf("\n
return 0; The value
value of num after calling tthe
he function = %d", num);
}
void add( int *n)
{
n = n + 10;
printf("\n The value
value of num in the called fun
function
ction = %d", n);
}
The output of this program is:
The value of num before
before calling the function = 2
The value of num in the called function = 112
2
The value of num after calling the function = 12
Scope of Variables
• A variable or a constant in C has four types of scope: block, function, file, and progra
program
m scope.
Variable Scope
Block Scope
Function Scope
• Func
Functi
tion
on scop
scope
e is ap
app
pli
liccable only
nly with
ith got
oto
o labe
labell nam
ames
es.. That is the
the prog
progrram
amme
merr can
ann
not have the
the same
same
la
labe
bell na
name
me in
insi
side
de a func
functi
tion
on..
Program Scope
• If you want that functions should be able to access some variables which are not passed to them as
arguments, then declare those variables outside any function block.
• Such variables are commonly known as global variables. Hence, global variables are those variables that
can be accessed from any point in the program.
#include<stdio.h>
int x = 10;
void print();
int main()
{ pr
prin
intf(
tf("\
"\n
n The
The valu
value
e of x in main
main()
() = %d",
%d", x);
x);
int x = 2;
printf("\n The value of local variable x in main() = %d", x);
print();
}
void print()
{ pr
prin
intf(
tf("\
"\n
n The
The valu
value
e of x in pr
prin
int(
t()) = %d"
%d",, x);
x);
}
Output:
The value of x in the main() = 10
The value of local variable x in main() = 2
The value of x in print() = 10
© Oxford University Press 2018. All rights reserved.
File Scope
• When a global variable is accessible until the end of the file, the variable is said to have file scope.
• To allow a variable to have file scope, declare that variable with the static keyword
keyword before specifying its
data type:
static
static iint
nt x = 10
10;;
• A global static variable can be used anywhere from the file in which it is declared but it is not accessible
Storage Classes
The storage class of a variable defines the scope (visibility) and lifetime of variables and/or functions
declared within a C Program.
It is used to determine the part of memory where storage space will be allocated for that variable or
It specifies the scope of the variable or function. That is, the part of the C program in which the variable
STORAGE CLASS
FEATURE
Auto Extern Register Static
Local: Accessible
within the function or
Acce
Accessi
ssibl
ble
e wiwith
thin
in
Acce
Access ssib
ible
le wi
with
thin
in th
the
e Accessib
Access ible
le within
within th
the
e bloc
block
k in whic
which
h it is
all
all prprog
ogrram fi
file
less
Accessibility function or block in which func
functi
tion
on or bloc
block
k in declared
th
that
at are a pa
part
rt of
it is declared which it is declared Gl
Glo
obal: Acce
ccess
ssib
iblle
the program
within the program in
which it is declared
Recursive Functions
• A recursive function is a function that calls itself to solve a smaller version of its task until a final call is
base case, in which the problem is simple enough to be solved directly without making any further calls
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
• Therefore,
Therefore, recursion is defining large and complex problems in terms of a smaller and more easily
solvable problem.
• In recursive functions, complicated problem is defined in terms of simpler problems and the simplest
problem is given explicitly.
Finding Factorial of
of a Number
Num ber using Recursion
PROBLEM SOLUTION
5! 5 X 4 X 3 X 2 X 1!
= 5 X 4! = 5 X 4 X 3 X 2 X 1
= 5 X 4 X 3! = 5 X 4 X 3 X 2
= 5 X 4 X 3 X 2! = 5 X 4 X 6
= 5 X 4 X 3 X 2 X 1! = 5 X 24
= 120
Types of Recursion
whether the function calls itself directly or indirectly (direct or indirect recursion)
the structure of the calling pattern (linear or tree-recur
tree-recursive)
sive)
Recursion
Direct Recursion
int
int Fu
Func
nc(( int
int n)
if(n==0)
return n;
else
return (Func(n-1));
Indirect Recursion
A function is said to be indirectly recursive if it contains a call to another function which ultimately calls
it. Look at the functions given below
below..
• These two functions are indirectly recursive as they both call each other.
int
int Fu
Func
nc1(
1(in
intt n) in
intt Fu
Func
nc2(
2(in
intt x)
{ {
if(n==0) return Func1(x-1);
return n; }
else
return Func2(n);
}
Tail Recursion
• A recursive function is said to be tail recursive if no operations are pending to be performed when the
• That is, when the called function returns, the returned value is immediately returned
returned from the calling
function.
• Tail recursive functions are highly desirable because they are much more efficient to use as in their
case, the amount of information
information that has to be stored on the system stack is independent of the
• In simple words, a recursive function is said to be linearly recursive when no pending operation involves
another recursive call to the function. For example, the factorial function is linearly recursive as the
pending operation involves only multiplication to be performed and does not involve another call to
Fact.
•
On the contrary, a recursive function is said to be tree recursive (or non-linearly recursive) if the pending
operation makes
makes another recursive call to the function. For example, the Fibonacci function (Fib) in
• Pros: Recursive solutions often tend to be shorter and simpler than non-recursive ones.
Recursion represents
represents like the original formula to solve a problem.
Recursion is implemented using system stack. If the stack space on the system is limited, recursion to a
deeper level will be difficult to implement.
Using a recursive function takes more memory and time to execute as compared to its non-recursive
counterpart.
Tower of Hanoi
• Tower of Hanoi is one of the main applications of a recursion. It says, "if you can solve n-1 cases, then
you can easily solve the nth case?"
A B C A B C
If there is only one ring, then simply move the ring from source to the destination
A B C
A B C A B C
If there are two rings, then first move ring 1 to the spare pole and then
move ring 2 from source to the destination. Finally move ring 1 from the
source to the destination
A B C © Oxford University Press 2018. All rights reserved.
A B C
A B C
A B C
A B C A B C
A B C
A B C A B C