Unit 5 Functionspart 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Session Objectives

Function Components

Parameter Passing
Passing Arrays to Functions
Recursive Functions

2
Function in C
A function is a block of code that performs a specific task. It has a name and it is reusable
.It can be executed from as many different parts in a program as required, it can also return
a value to calling program.
All executable code resides within a function. It takes input, does something with it, then
give the answer.
A computer program cannot handle all the tasks by itself. It requests other program like
entities called functions in C. We pass information to the function called arguments which
specified when the function is called. A function either can return a value or returns nothing.
Function is a subprogram that helps reduce coding.

return_type function_name (argument list)


{
Set of statements – Block of code
}

3
Why use Function
Basically there are two reasons because of which we use functions

1. Writing functions avoids rewriting the same code over and over.
For example - if you have a section of code in a program which
calculates the area of triangle. Again you want to calculate the
area of different triangle then you would not want to write the
same code again and again for triangle then you would prefer to
jump a "section of code" which calculate the area of the triangle
and then jump back to the place where you left off. That section of
code is called ..........„ function'.
2. Using function it becomes easier to write a program and keep
track of what they are doing. If the operation of a program can be
divided into separate activities, and each activity placed in a
different function, then each could be written and checked more
or less independently. Separating the code into modular functions
also makes the program easier to design and understand.
GSR,cse4
How Function’s Work
 Once a function is defined and called, it takes some data from the calling
function and returns a value to the called function.

 When ever a function is called, control passes to the called function and
working of the calling function is stopped.

 When the execution of the called function is completed, a control returns


back to the calling function and executes the next statement.

 The values of actual arguments passed by the calling function are received
by the formal arguments of the called function.

 The number of actual and formal arguments should be the same. If the
formal arguments are more than the actual arguments then the extra arguments
appear as garbage.

 The function operates on formal arguments and sends back the result to the
calling function.
5
Calling Function and Called Function
Def:- The function which is referring another function is called “calling
function”.

Def:- The function which is referenced by another function is called “called


function”

Actual Arguments and Formal Arguments


Def:- The arguments of calling functions are called “actual arguments”.

Def:- The arguments of called function are “formal arguments”.

Local Variables and Global Variables


Local variables:-
The local variables are defined within the body of the function or the block.
Other function cannot access these variables.

Global variables:-
Global variables are defined outside the main() function. Multiple functions
can use them.
Library Function’s in C
C provides library functions for performing some operations. These
functions are present in the c library and they are predefined.

For example sqrt() is a mathematical library function which is used for


finding the square root of any number .The function scanf and printf()
are input and output library function similarly we have strcmp() and
strlen() for string manipulations. To use a library function we have to
include some header file using the preprocessor directive #include.

For example to use input and output function like printf() and scanf() we
have to include stdio.h, for math library function we have to include
math.h for string library string.h should be included.

8
User defined Function’s in C
A user can create their own functions for performing any specific
task of program are called user defined functions. To create and
use these function we have to know these 3 elements.

1. Function Declaration
2. Function Definition
3. Function Call

Gsr,cse
User defined Function’s in C
1. Function Declaration
The program or a function that calls a function is referred to as the calling program or calling
function. The calling program should declare any function that is to be used later in the program
this is known as the function declaration or function prototype.

2. Function Definition
The function definition consists of the whole description and code of a function. It tells that what
the function is doing and what are the input outputs for that. A function is called by simply writing
the name of the function followed by the argument list inside the parenthesis. Function definitions
have two parts:
Function Header
The first line of code is called Function Header. int sum( int x, int y)
It has three parts
(i). The name of the function i.e. sum
(ii). The parameters of the function enclosed in parenthesis
(iii). Return value type i.e. int
Function Body
Whatever is written with in { } is the body of the function.

3. Function Call
In order to use the function we need to invoke it at a required place in the program. This is known
as the function call.
20
Parameter Passing
Most programming languages have 2 strategies to pass parameters. They are
i. Call by value
ii. Call by address
Pass by value (or) call by value :-

In this method calling function sends a copy of actual values to called function, but the
changes in called function does not reflect the original values of calling function.

Pass by reference (or) call by address :-

In this method calling function sends address of actual values as a parameter to called
function, called function performs its task and sends the result back to calling function.
Thus, the changes in called function reflect the original values of calling function. To
return multiple values from called to calling function we use pointer variables.

Calling function needs to pass ..„&‟ operator along with actual arguments and called
function need to use „*‟ operator along with formal arguments. Changing data through
an aaddress variable is known as indirect access and „*‟ is represented as indirection
operator.
Pass by Valur (or) Call By Value
Pass by value (or) call by value :-
Function call by value is the default way of calling a function in C
programming. Before we discuss function call by value, lets understand the
terminologies that we will use while explaining this:
Actual parameters: The parameters that appear in function calls.
Formal parameters: The parameters that appear in function declarations.

When we pass the actual parameters while calling a function then this is known
as function call by value. In this case the values of actual parameters are copied
to the formal parameters. Thus operations performed on the formal parameters
don‟t reflect in the actual parameters.

Call By Value: In this parameter passing method, values of actual parameters


are copied to function‟s formal parameters and the two types of parameters are
stored in different memory locations. So any changes made inside functions are
not reflected in actual parameters of caller.
Pass by Reference (or) Call by address
Pass by reference (or) call by address :-
Before we discuss function call by reference, lets understand the terminologies that we
will use while explaining this:
Actual parameters: The parameters that appear in function calls.
Formal parameters: The parameters that appear in function declarations.

When we call a function by passing the addresses of actual parameters then this way of
calling the function is known as call by reference. In call by reference, the operation
performed on formal parameters, affects the value of actual parameters because all the
operations performed on the value stored in the address of actual parameters. It may
sound confusing first but the following example would clear your doubts.

Call by Reference: Both the actual and formal parameters refer to same locations, so any
changes made inside the function are actually reflected in actual parameters of caller.

Calling function needs to pass ..„&‟ operator along with actual arguments and called
function need to use „*‟ operator along with formal arguments. Changing data through
an aaddress variable is known as indirect access and „*‟ is represented as indirection
operator.
Pass by value (or) call by value Pass by reference (or) call by address
#include<stdio.h> #include<stdio.h>
void fun1(int, int); void fun1(int *, int *);
void main( ) void main( )
{ {
int a=10, b=15; int a=10, b=15;
Printf(“values of a and b before function call \n”); Printf(“values of a and b before function call \n”);
printf(“a=%d,b=%d”, a,b); printf(“a=%d,b=%d”, a,b);
fun1(a,b); fun1(&a,&b);
Printf(“values of a and b after function call \n”); Printf(“values of a and b after function call \n”);
printf(“a=%d,b=%d”, a,b); printf(“a=%d,b=%d”, a,b);
} }
void fun1(int a, int b) void fun1(int *a, int *b)
{ {
a=a+10; *a= *a+10;
b= b+20; *b= *b+20;
Printf(“values of a and b incalled function \n”); Printf(“values of a and b incalled function \n”);
printf(“a=%d,b=%d”, a,b); printf(“a=%d,b=%d”, a,b);
} }
values of a and b before function call values of a and b before function call
a=10 b=15 a=10 b=15
values of a and b incalled function values of a and b incalled function
a=20 b= 35 a=2000 b= 3000
values of a and b after function call values of a and b after function call
a=10 b=15 a=20 b=35
Main ()
Main ()

2000 a 10 2000 a 10 20
2001 2001
2002 2002
: :
: :
3000 b 15 3000 b 15 35

fun1() fun1()

3500 a 10 20 3500 a 2000


3501 3501
3502 3502
: :
: :
4000 b 15 35 4000 b 3000

25
Pass by value (or) call by value Pass by reference (or) call by address
#include<stdio.h> #include<stdio.h>
void swap(int, int); void swap(int *, int *);
void main( ) void main( )
{ {
int a=10, b=15; int a=10, b=15;
Printf(“values of a and b before function call \n”); Printf(“values of a and b before function call \n”);
printf(“a=%d,b=%d”, a,b); printf(“a=%d,b=%d”, a,b);
swap(a,b); swap(&a,&b);
Printf(“values of a and b after function call \n”); Printf(“values of a and b after function call \n”);
printf(“a=%d,b=%d”, a,b); printf(“a=%d,b=%d”, a,b);
} }
void swap(int a, int b) void swap(int *x, int *y)
{ {
int temp; int temp;
temp =a; temp = *x;
a=b; *x=*y;
b= temp; *x= temp;
Printf(“values of a and b incalled function \n”); Printf(“values of a and b incalled function \n”);
printf(“a=%d,b=%d”, a,b); printf(“a=%d,b=%d”, *x,*y);
} }
values of a and b before function call values of a and b before function call
a=10 b=15 a=10 b=15
values of a and b incalled function values of a and b incalled function
a=15 b= 10 x=15 y= 10
values of a and b after function call values of a and b after function call
a=10 b=15 a=15 b=10
Main ()
Main ()

2000 a 10 2000 a 10 15
2001 2001
2002 2002
: :
: :
3000 b 15 3000 b 15 10

fun1() fun1()

3500 a 10 15 3500 a 2000


3501
3501
3502 temp 10 3502 temp 10
: :
: :
4000 b 15 10 4000 b 3000

27
STORAGE CLASSES
Variables in C differ in behavior. The behavior depends on the storage
class a variable may assume. From C compiler‟s point of view, a variable
name identifies some physical location within the computer where the
string of bits representing the variable‟s value is stored. There are four
storage classes in C:
1. Automatic storage class
2. External storage class
3. Static storage class
4. Register storage class

Syntax:-
storage_class var_data_type var_name;

28
1. Automatic storage class
 This is the default storage class for all the variables declared
inside a function or a block.
 Hence, the keyword auto is rarely used while writing programs
in C language.
 Auto variables can be only accessed within the block/function
they have been declared and not outside them (which defines their
scope).
 Of course, these can be accessed within nested blocks within the
parent block/function in which the auto variable was declared.
 They are assigned a garbage value by default whenever they are
declared.

29
2. Extern storage class
 Extern storage class simply tells us that the variable is defined
elsewhere and not within the same block where it is used.
 Basically, the value is assigned to it in a different block and this
can be overwritten/changed in a different block as well.
 So an extern variable is nothing but a global variable initialized
with a legal value where it is declared in order to be used elsewhere.
 It can be accessed within any function/block.
 Also, a normal global variable can be made extern as well by
placing the „extern‟ keyword before its declaration/definition in any
function/block.
 This basically signifies that we are not initializing a new variable
but instead we are using/accessing the global variable only.
 The main purpose of using extern variables is that they can be
accessed between two different files which are part of a large
program.
30
3. Static storage class
 This storage class is used to declare static variables which
are popularly used while writing programs in C language.
 Static variables have a property of preserving their value
even after they are out of their scope! Hence, static variables
preserve the value of their last use in their scope. So we can
say that they are initialized only once and exist till the
termination of the program.
 Thus, no new memory is allocated because they are not
re-declared.
 Their scope is local to the function to which they were
defined.
 Global static variables can be accessed anywhere in the
program. By default, they are assigned the value 0 by the
compiler.

31
4. Register storage class
 This storage class declares register variables which have
the same functionality as that of the auto variables. The only
difference is that the compiler tries to store these variables in
the register of the microprocessor if a free register is
available. This makes the use of register variables to be
much faster than that of the variables stored in the memory
during the runtime of the program. If a free register is not
available, these are then stored in the memory only. Usually
few variables which are to be accessed very frequently in a
program are declared with the register keyword which
improves the running time of the program. An important and
interesting point to be noted here is that we cannot obtain the
address of a register variable using pointers.

32
STORAGE CLASS

STORAGE STORAGE INITIAL KEYWORD SCOPE LIFETIME


SPECIFIER VALUE

AUTO Main Memory Garbage value auto With in block End of Block

EXTERN Main Memory Zero extern Entire Till End of


Program Program

STATIC Main Memory Zero static With in block Till End of


Program

REGISTAR Registar Garbage value register With in block End of Block

33
Recursion
Recursion is a process by which a function calls itself repeatedly,
until some specified condition has been satisfied.

When a function calls itself, a new set of local variables and


parameters are allocated storage on the stack, and the function code
is executed from the top with these new variables. A recursive call
does not make a new copy of the function. Only the values being
operated upon are new. As each recursive call returns, the old local
variables and parameters are removed from the stack, and execution
resumes immediately after the recursive call inside the function.

The main advantage of recursive functions is that we can use them


to create clearer and simpler versions of several programs.

34
Recursion
Recursion is a process by which a function calls itself repeatedly, until some specified
condition has been satisfied.
The process in which a function calls itself directly or indirectly is called recursion
and the corresponding function is called as recursive function. Using recursive algorithm,
certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi
(TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.

int main()
{
rec(); In the beginning main() function
... called rec(), then inside rec() function,
return 0; it called itself again. As you can guess
} this process will keep repeating
indefinitely. So, in a recursive
void rec() function, there must be a terminating
{ condition to stop the recursion. This
statement 1; condition is known as the base
... condition.
rec();
}
35
Recursion
Recursion is a process by which a function calls itself repeatedly,
until some specified condition has been satisfied.
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
36
Recursion
The recursion continues until some condition is
met to prevent it.
To prevent infinite recursion, if...else statement (or
similar approach) can be used where one branch
makes the recursive call, and other doesn't.
#include <stdio.h>
int sum(int n);
void main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
}
int sum(int n)
{
if (n != 0) // sum() function calls itself
return n + sum(n-1);
else OUTPUT
return n; Enter a positive integer:3
} sum = 6
37
Find the factorial of a number using Recursion
#include <stdio.h>
unsigned long long int factorial(unsigned int i)
{
if(i <= 1)
return 1;
else
return i * factorial(i - 1);
}
int main()
{
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}

Output
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600
Fibonacci Series : The following example generates the Fibonacci series for a given
number using a recursive function −
#include <stdio.h>
int fibonacci(int i)
{
if(i == 0)
return 0;
else
if(i == 1)
return 1;
else
return fibonacci(i-1) + fibonacci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++)
printf("%d\t", fibonacci(i));
return 0;
}
OUTPUT
0 1 1 2 3 5 8 13 21 34
39
Passing Arrays as Function Arguments in C
If you want to pass a single-dimension array as an argument in a function, you would have to declare
a formal parameter in one of following three ways and all three declaration methods produce similar
results because each tells the compiler that an integer pointer is going to be received. Similarly, you
can pass multi-dimensional arrays as formal parameters.

Way-1 : Formal parameters as a pointer


void myFunction(int *param)
{
...
}

Way-2: Formal parameters as a sized array


void myFunction(int param[10])
{
...
}

Way-3 : Formal parameters as an unsized array


void myFunction(int param[])
{
...
}
40
Now, consider the following function, which takes an array as an argument along with
another argument and based on the passed arguments, it returns the average of the numbers
passed through the array as follows −
#include <stdio.h>
double getAverage(int arr[], int size); /* function declaration */
int main ()
{
int balance[5] = {1000, 2, 3, 17, 50}; /* an int array with 5 elements */
double avg;
avg = getAverage( balance, 5 ) ; /* pass pointer to the array as an argument */
printf( "Average value is: %f ", avg ); /* output the returned value */
return 0;
}
double getAverage(int arr[], int size)
{
int i;
double avg;
double sum = 0;
for (i = 0; i < size; ++i)
sum += arr[i];
avg = sum / size;
return avg;
}
When the above code is compiled together and executed, it produces the following result −
Average value is: 214.400000
Categories Of Function’s
A function depending on whether arguments are present or not and
whether a value is returned or not may belong to any one of the
following categories:

I. Functions with no arguments and no return values.

II. Functions with arguments and no return values.

III. Functions with arguments and return values.

IV. Functions with no arguments and return values.


Function’s with no arguments and no return values

There is no data communication between the calling portion of a


program and a called function block. The function is invoked bya calling
environment by not passing any formal arguments and the function also
does not return back any value to the caller.

function1() function2()
{ {
---------------------
No Input
---------------------
--------------------- ---------------------
--------------------- ---------------------
function2(); /* function call*/ ---------------------
---------------------
No Output
---------------------
---------------------
}
}

No data communication between functions


Function’s with no arguments and no return values
#include<stdio.h>
#include <conio.h>
void maximum();
{
int x,y,z,max;
printf( “ Enter three Numbers \n”);
scanf(“%d%d%d”, &x,&y,&z);
max = x;
if(y > max)
max = y;
if(z > max)
max = z;
printf(“Maximum = %d \n”,max);
}
void main()
{ Input- Output
clrscr();
maximum(); Enter three Numbers
1 2 3
getch();
Maximum = 3
}
Function’s with arguments and no return values

The second type of user defined function passes some formal arguments
to a function but the function does not return back any value to the caller.
It is an one – way data communication between the calling portion of a
program and a called function block.

function1() Values function2(a)


{ of arguments {
--------------------- ---------------------
--------------------- ---------------------
--------------------- ---------------------
function2(x); /* function call*/ No return values ---------------------
--------------------- ---------------------
---------------------
}
}

One – way data communication between functions


Function’s with arguments and no return values
#include<stdio.h>
#include <conio.h>
void maximum(int, int, int);
void main()
{ int x,y,z;
clrscr();
printf( “ Enter three Numbers \n”);
scanf(“%d%d%d”, &x,&y,&z);
maximum(x,y,z);
getch();
}
void maximum(int a, int b, int c)
{ int max;
max = a;
if(b > max)
max = b; Input- Output
if(c > max)
max = c; Enter three Numbers
1 2 3
printf(“Maximum = %d \n”,max);
Maximum = 3
}
Function’s with arguments and with return values

The third type of user defined function passes some formal arguments to
a function from a calling portion of the progra and the computed value, if
anyy, is transferred back to the caller. Data are communicated between
the calling portion of a program and a called function block.

function1() Values function2(a)


{ {
of arguments ---------------------
---------------------
--------------------- ---------------------
--------------------- ---------------------
function2(x); /* function call*/ ---------------------
Function results ---------------------
---------------------
--------------------- return(z);
}
}

Two – way data communication between functions


Function’s with arguments and with return values
#include<stdio.h>
#include <conio.h>
int maximum(int x, int y, int z);
void main()
{ int x,y,z,maxi;
clrscr();
printf( “ Enter three Numbers \n”);
scanf(“%d%d%d”, &x,&y,&z);
maxi = maximum(x,y,z);
printf(“Maximum = %d \n”,maxi);
getch();
}
int maximum(int x, int y, int z)
{ int max;
max = x;
if(y > max)
Input- Output
max = y;
if(z > max) Enter three Numbers
max = z; 1 2 3
return(max); Maximum = 3
}
Function’s with no arguments and return values

The fourth type of user defined function, the function is invoked by a


calling environment by not passing any formal arguments to a function
but the computed value, if any, is transferred back to the caller. Data are
communicated between the calling portion of a program and a called
function block in one way.

function1() function2()
{ {
---------------------
No Input ---------------------
--------------------- ---------------------
--------------------- ---------------------
function2(); /* function call*/ ---------------------
--------------------- Function results ---------------------
--------------------- return(z);
}
}

One – way data communication between functions


Function’s with no arguments and return values
#include<stdio.h>
#include <conio.h>
int maximum();
void main()
{ int max;
clrscr();
max = maximum();
printf(“Maximum = %d \n”,max);
getch();
}
int maximum()
{ int x,y,z,max;
printf( “ Enter three Numbers \n”);
scanf(“%d%d%d”, &x,&y,&z);
max = x;
if(y > max)
max = y; Input- Output
if(z > max)
Enter three Numbers
max = z; 1 2 3
return(max); Maximum = 3
}

You might also like