Module3 - Functions - PCD Notes C Programming
Module3 - Functions - PCD Notes C Programming
Module3 - Functions - PCD Notes C Programming
Module 3
FUNCTIONS
Definition:
Advantages of functions
Types of functions
1. Built in Functions
These functions are defined in the library of C compiler which are used
frequently in the C program. C supports many built in functions like
Mathematical functions
String manipulation functions
Input and output functions
Memory management functions
Error handling functions
Function Structure
The function structure consists of two parts
1. function header
2. function body
1. Function header
It consists of three parts
Syntax: return_type function_name( parameter or without parameters);
The return value of the function
The name of the function
The parameters of the functions may be included or not
Exa: void add( int a, int b);
In the above example the return type of the function is void, the name of the
function is add and the parameters are 'a' and 'b' of type integer.
2. Function body
The function body consists of the set of instructions enclosed between {
and } .
Generally while representing the function we can include the functions in the
program as
Function Call
Function Definitions
Function Declaration
1. Function Call: a function call also termed as signature of the function is the
statement which calls the function. It is declared in the main program. A function
call is defined as function name followed by semicolon.
Exa:
void main()
{
add(a,b);
}
Note: A function call is nothing but invoking a function at the required place in
the program to achieve a specific task.
without prototyping
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b;
printf(“\n enter the two numbers a and b”);
scanf(“%d%d”, &a, &b);
add(a,b); // function call
getch();
}
with prototyping
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b;
printf(“\n enter the two numbers a and b”);
scanf(“%d%d”, &a, &b);
add(a,b); // function call
getch();
}
void add(int a, int b) // function definition
{
int x;
x=a+b;
printf(“\n the sum is %d”, x);
}
Note: the function prototyping can be specified in different ways if parameters are
passed
1. Only the data type can be specified instead of specifying the variable name
with data type.
Exa: void add(int a, int b); can also be written as void add( int, int);
2. If arrays are used as parameters then we have to specify the ranging values.
Exa: void add( int a[ ], int b[ ]); can be specified as void add( int [ ], int [ ]);
A function that is invoked or called when the program is being executed is called
“called function” and the invoking function is called “calling function”.
#include<stdio.h>
#include<conio.h>
In the above program we are calling a function add() from the main function, that
means we are invoking a function add(). We are calling the function add() from
the main function then main() is “calling function” and invoked function add() is
called as “called function”.
Formal Parameters:
The variables defined in the function header of function definition are
called formal parameters. All the variables should be separately declared and
Actual Parameters:
The variables that are used when a function is invoked are called actual
parameters. Using actual parameters, the data can be transferred to the
function. The corresponding formal arguments in the function definition
receive them. The actual parameters and formal parameters must match in
number and type of data.
Example:
#include<stdio.h>
void swap(int,int);
void main()
{
int a,b;
printf("enter values for a and b:");
scanf("%d %d",&a,&b);
printf("the values before swapping are a=%d b=%d \n",a,b);
swap(a,b); // The variables in Function call are known as Actual
parameters
printf("the values after swapping are a=%d b=%d \n",a,b);
}
void swap(int c, int d) // The variables in function header are known as
Formal parameters
{
int temp;
temp=c;
c=d;
d=temp;
}
Example:
#include<stdio.h>
void add();
void main()
{
add(); / * Function Call */
}
void add() /* Function Header */
{
int a,b,c;
printf(“enter values for a and b:”);
scanf(“%d %d”,&a,&b);
c = a+b;
printf(“sum is:%d”,c);
}
When the function add() is called , the values for a and b are read, they
are added and the resulted is printed on the monitor.
Example:
#include<stdio.h>
void add(int m, int n);
void main()
{
int a,b;
printf(“enter values for a and b:”);
scanf(“%d %d”,&a,&b);
add(a,b); / * Function Call */
}
void add(int m,int n) /* Function Header */
{
int c;
c = m+n;
printf(“sum is:%d”,c);
}
Example :
#include<stdio.h>
int add();
void main()
{
int result;
result=add(); / * Function Call */
printf(“sum is:%d”,result);
}
int add() /* Function Header */
{
int a,b,c;
printf(“enter values for a and b:”);
scanf(“%d %d”,&a,&b);
c = a+b;
return c;
}
Example:
#include<stdio.h>
int add(int a, int b);
void main()
{
int a,b,result;
printf(“enter values for a and b:”);
scanf(“%d %d”,&a,&b);
result=add(a,b); / * Function Call */
printf(“sum is:%d”,result);
}
int add(int m,int n) /* Function Header */
{
int c;
c = m+n;
return c;
}
Call by value:
In call by value, the values of actual parameters are copied into
formal parameters, that is formal parameters contain only a copy of the
actual parameters. So, even if the values of the formal parameters changes
in the called function, the values of the actual parameters are not changed.
Example:
#include<stdio.h>
void swap(int,int);
void main()
{
int a,b;
printf("enter values for a and b:");
scanf("%d %d",&a,&b);
printf("the values before swapping are a=%d b=%d \n",a,b);
swap(a,b);
printf("the values after swapping are a=%d b=%d \n",a,b);
getch().
}
{
int temp;
temp=c;
c=d;
d=temp;
}
Execution starts from function main() and we will read the values for
variables a and b, assume we are reading 10 and 20 for a and b
respectively.
We will print the values before swapping it will print 10 and 20.
The function swap() is called with actual parameters a and b whose
values are 10 and 20.
In the function header of function swap(), the formal parameters c and d
receive the values 10 and 20.
In the function swap(), the values of c and d are exchanged.
But, the values of actual parameters a and b in function main() have
not been exchanged.
Call by Reference
In Call by reference, when a function is called, the addresses of
actual parameters are sent. In the called function, the formal parameters
should be declared as pointers with the same type as the actual
parameters. The addresses of actual parameters are copied into formal
parameters. Using these addresses the values of the actual parameters can
be changed.
The concept of call by reference can be explained by considering the
following program.
Example:
#include<stdio.h>
void swap(int *a,int *b);
void main()
{
int a,b;
printf("enter values for a and b:");
scanf("%d %d",&a,&b);
printf("the values before swapping are a=%d b=%d \n",a,b);
swap(&a,&b);
printf("the values after swapping are a=%d b=%d \n",a,b);
getch();
}
void swap(int *c,int *d)
{
int temp;
temp=*c;
*c=*d;
*d=temp;
}
The sequences of operations that are carried out during the execution of the
program are:
Execution starts from function main() and assume that we are reading
values 10 and 20 for variables a and b. We will print the values before
swapping it will print 10 and 20.
The function swap() is called by sending the addresses of a and b.
In the function header of function swap, the formal parameters c and d
declared using *
operator holds the addresses of a and b.
In the function swap(), using *c and *d we can access the values of a
and b and they are exchanged.
NOTE:
Pointer: A pointer is a variable that is used to store the address of another variable.
Syntax: datatype *variablename;
Example: int *p;
#include<stdio.h>
void main()
{
int a ,*p;
p=&a;
}
In the above program p is a pointer variable, which is storing the address of variable a.
Execution is slower since all the values Execution is faster since only addresses are
have to be copied into formal copied.
parameters.
Global Scope:
The variables that are defined outside a block have global scope. That is
any variable defined in global area of a program is visible from its definition
until the end of the program. For Example, the variables declared before all
the functions are visible everywhere in the program and they have global
scope.
Local Scope
The variables that are defined inside a block have local scope. They exist
only from the point of their declaration until the end of the block. They are
not visible outside the block.
For Example
The life span of a global variable is the life span of the program.
The life span of local variables is the life span of the function, they
are created.
Differences between global variable and local variables
Global variables are declared outside Local variables are declared inside a
all the functions function
Global variables can be accessed by all Local variables can be accessible to only
the functions or modules in the the respective module or function where
program they are declared.
The life time of the global variable will The life time of the local variables
be for the entire duration of the limited only to the exeution of the
execution of program function where they are declared.
Storage Classes
A storage class defines the scope (visibility) and life time of variables and/or
functions within a C Program.
auto - Storage Class: auto is the default storage class for all local
variables
Example:
void main()
{
int count;
auto int count;
}
The example above defines two variables with the same storage class. auto
can only be used within functions i.e local variables.
Example:
MR. SUKRUTH GOWDA M A, Dept., of CS&E, RLJIT 18
Programming in C and Data Structures 14PDS13
void main()
{
register int count;
}
Register should only be used for variables that require quick access - such
as loops.
Static-Storage Class : The variables that are declared using the keyword
static are called static variables. The static variables can be declared
outside the function and inside the function. They have the characteristics
of both local and global variables.
Static can also be defined within a function. If this is done the variable is
initialized at run time but is not reinitialized when the function is called.
This inside a function static variable retains its value during various calls.
/**********Example **********/
#include<stdio.h>
void display();
void main()
{
int i;
for(i=1;i<=5;i++)
display();
getch();
}
void display()
{
static int n=0;
n=n+1;
printf("the value of n is:%d \n",n);
}
In the above example, we are calling display() function 5 times, but in the
display() function we are initializing variable n to 0. Since the variable n is
static it will be initialized only once.
Extern –Storage Class : The variables that are declared using the keyword
extern are called extern variables. These variables are declared before all
functions in global area of the program.
Location of functions
While writing the program making use of function the question arises as
to where the function has to be placed in the program. Generally function
placement in the program can be done in three possible ways.
In the first case the definition of the function appears before the main program's
call to the function, so that by the time compiler reaches the function call it will
be knowing what to expect.
Function definition
Main program
In the second case the function appears after the main program. In this case the
compiler priorly doesn’t know about the function exact when it encounters the
function call in the main program. To overcome this we are specifying the
function prototyping.
Function prototyping
Main program
Function definition
In the last case we maintain function in a separate file and main program in a
separate file, compile them separately and a link will be provided between the two
for communication. This is the way how exactly the library functions work.
File 1 File 2
Main program
Recursion
Example:
void recursion()
{
recursion(); /* function calling itself */
}
In the above example we have not return the exit condition, so the function
is in infinite loop. So, we need to be careful to define an exit function when
we are implementing recursive functions.
Example 1.
/******* Factorial of a given number using Recursion ******/
#include<stdio.h>
int fact(int m);
void main()
{
int n,result;
printf("enter number:");
scanf("%d",&n);
result=fact(n);
printf("the factorial of a number is:%d",result);
getch();
}
int fact(int m)
{
if(m==1)
return 1;
else
return (m*fact(m-1));
}
Notice how in function factorial we included a call to itself, but only if the
argument passed was greater than 1, since otherwise the function would
perform an infinite recursive loop in which once it arrived to 0 it would
continue multiplying by all the negative numbers (probably provoking a
stack overflow error on runtime).
This function has a limitation because of the data type we used in its
design (long) for more simplicity. The results given will not be valid for
values much greater than 10! Or 15! Depending on the system you compile
it.
a) Base case: The statement that solves the problem is called base case.
Every recursive function must have at least one base case. It is a special
case whose solution can be obtained without using recursion.
A base case serves two purposes:
i). It act as a terminating condition.
ii). the recursive function obtains the solution from the base case it
reaches.
n!=1 if n=0
b) General case: The statement that reduces the size of the problem is
called general case. This is done by calling the same function with
reduced size.
fact(n)=
n* fact(n-1)! Otherwise // General case
Example 2:
Fibonacci numbers:
Fibonacci numbers are a series of numbers such that each number is the
sum of the two previous numbers except the first and second number.
Example 3:
Tower of Hanoi:
The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower). It
consists of three rods, and a number of disks of different sizes which can
slide onto any rod. It starts with the disks in a neat stack in ascending
order of size on one rod, the smallest at the top, thus making a conical
shape.
The objective of the puzzle is to move the entire stack to another rod,
obeying the following simple rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack i.e. a disk can only be moved if it is the
uppermost disk on a stack.
3. No disk may be placed on top of a smaller disk.
With three disks, the puzzle can be solved in seven moves. The minimum
number of moves required to solve a Tower of Hanoi puzzle is 2n - 1, where n is
the number of disks.
For example:
label the pegs A, B, C — these labels may move at different steps
let n be the total number of discs
number the discs from 1 (smallest, topmost) to n (largest, bottommost)
At the top level, we will want to move the entire tower, so we want to move
disks 5 and smaller from peg A to peg B. We can break this into three basic
steps.
Move disks 4 and smaller from peg A (source) to peg C (spare), using peg
B (dest) as a spare. How do we do this? By recursively using the same
procedure. After finishing this, we'll have all the disks smaller than disk
4 on peg C. (Bear with me if this doesn't make sense for the moment -
we'll do an example soon.)
In pseudocode, this looks like the following. At the top level, we'll call
IF disk == 0, THEN:
move disk from source to dest
ELSE:
MoveTower(disk - 1, source, spare, dest) // Step 1 above
move disk from source to dest // Step 2 above
MoveTower(disk - 1, spare, dest, source) // Step 3 above
END IF
Note:
1. Recursion is not possible, where are called thousands of time.
2. Function can be used in expressions, more than once; provided
functions should not have void return type.
3. Even we can identify the function in mathematical view
Ex: (6, 4), (1, 0), (2,3), (6,10) : This is not a function because here 6 is
appeared 2 times