UNIT IVfunctions notes
UNIT IVfunctions notes
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program. The function is also known as procedure
or subroutine in other programming languages.
Advantage of functions in C
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in a
program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.
Function Aspects
o Function call Function can be called from anywhere in the program. The parameter list
must not differ in function calling and function declaration. We must pass the same
number of functions as it is declared in the function declaration.
o Function definition It contains the actual statements which are to be executed. It is the
most important aspect to which the control comes when the function is called. Here, we
must notice that only one value can be returned from the function.
1
3 Function return_type function_name (argument list) {function
definition body;}
Types of Functions
1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code. Ex: add(), sub(), fact(), GCD(),…
Example:
c=n*n*n; return(c);
Return Value
A C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type. A function can return only one value after
execution.
2
Different types of function calling:
A function may or may not accept any argument. It may or may not return any value. Based on
these facts, There are four different aspects of function calls.
3
}
void add(int x,int y) //function definition
{
int z;
z=x+y;
printf("\n result=%d\n",z);
}
3. function without arguments and with return value
//function without arguments and return values
#include<stdio.h>
int add(); //function declaration
void main()
{
int c;
c=add(); //function call
printf("\n result=%d\n",c);
}
int add() //function definition
{
int a,b,c;
printf("\n Enter a,b values:");
scanf("%d%d",&a,&b);
c=a+b;
return c;
}
4. function without arguments and without return value
#include<stdio.h>
void add(); //function declaration
void main()
{
add(); //function call
printf("\n End of main function”);
4
}
void add() //function definition
{
int a,b,c;
printf("\n Enter a,b values:");
scanf("%d%d",&a,&b);
c=a+b;
printf(“\n result=%d,c);
}
Passing parameters to a function:
Firstly, what are parameters?
parameters are the values that are passed to a function for processing.
Let's understand call by value and call by reference in c language one by one.
5
Call by value in C
In call by value method, the value of the actual parameters is copied into the formal parameters.
In other words, we can say that the value of the variable is used in the function call in the call by
value method.
In call by value method, we can not modify the value of the actual parameter by the formal
parameter.
In call by value, different memory is allocated for actual and formal parameters since the value
of the actual parameter is copied into the formal parameter.
The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.
Let's try to understand the concept of call by value in c language by the example given below:
//call by value
#include<stdio.h>
void swap(int,int);
void main()
{
int a,b,c;
printf("\n Enter a,b values:");
scanf("%d%d",&a,&b);
printf("\n Before swapping a=%d\tb=%d\n",a,b);
swap(a,b);
printf("\n After swapping a=%d\tb=%d\n",a,b);
}
void swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
}
Call by reference in C
In call by reference, the address of the variable is passed into the function call as the actual
parameter.
The value of the actual parameters can be modified by changing the formal parameters since the
address of the actual parameters is passed.
In call by reference, the memory allocation is similar for both formal parameters and actual
parameters. All the operations in the function are performed on the value stored at the address of
the actual parameters, and the modified value gets stored at the same address.
6
#include<stdio.h>
void swap(int *,int *);
void main()
{
int a,b,c;
printf("\n Enter a,b values:");
scanf("%d%d",&a,&b);
printf("\n Before swapping a=%d\tb=%d\n",a,b);
swap(&a,&b);
printf("\n After swapping a=%d\tb=%d\n",a,b);
}
void swap(int *x,int *y)
{
int t;
t = *x;
*x = *y;
*y =t;
}
Recursion
Firstly, what is nested function?
When a function invokes another function then it is called nested
function. But, When a function invokes itself then it is called
recursion.
NOTE: In recursion, we must include a terminating condition so that it won't execute to
infinite time.
Recursion is the process which comes into existence when a function calls a copy of itself to
work on a smaller problem. Any function which calls itself is called recursive function, and such
function calls are called recursive calls. Recursion involves several numbers of recursive calls.
However, it is important to impose a termination condition of recursion. Recursion code is
shorter than iterative code however it is difficult to understand.
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be
defined in terms of similar subtasks. For Example, recursion may be applied to sorting,
searching, and traversal problems.
Generally, iterative solutions are more efficient than recursion since function call is always
overhead. Any problem that can be solved recursively, can also be solved iteratively. However,
some problems are best suited to be solved by the recursion, for example, tower of Hanoi,
Fibonacci series, factorial finding, etc.
Advantages:
7
Disdvantages(limitations)
void main()
{
int n,f;
printf("\n Enter n value:");
scanf("%d",&n);
f=fact(n); //function call
printf("\n factorial=%d\n",f);
}
int fact(int n) //function definition
{
if(n==1)
return 1;
else
return n*fact(n-1);
}
We can understand the above program of the recursive method call by the figure given
below:
8
2. //GCD using recursion
#include<stdio.h>
void main()
{
int a,b,g;
printf("\n Enter a,b values:");
scanf("%d%d",&a,&b);
g=gcd(a,b); //function call
printf("\n GCD=%d\n",g);
}
int gcd(int a,int b) //function definition
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
9
{
int i,n;
printf("\n enter n value:");
scanf("%d",&n);
printf("\n fibonaci series:\n");
for (i = 0; i < n; i++)
printf("\t%d", fibonaci(i));
}
int fibonaci(int i)
{
if(i == 0)
return 0;
if(i == 1)
return 1;
//passing arrays into function(to find the average of the elements in the array)
#include<stdio.h>
float average(int [],int);
void main()
{
int a[100],n,i;
float avg;
printf("\n Enter size of the array:");
scanf("%d",&n);
printf("\n Enter elements of the array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
avg=average(a,n);
printf("\n average=%f\n",avg);
}
10
2. //passing arrays into function(to find max and min elements in the array)
#include<stdio.h>
int minimum(int [],int);
int maximum(int [],int);
void main()
{
int a[100],n,i,min,max;
min=minimum(a,n);
max=maximum(a,n);
printf("\n mininum=%d\t maximum=%d",min,max);
}
for(i=1;i<n;i++)
{
if(a[i]<min)
min=a[i];
}
return min;
}
for(i=1;i<n;i++)
{
if(a[i]>max)
max=a[i];
}
return max;
}
The exact size of array is unknown untill the compile time,i.e., time when a compier
11
compiles code written in a programming language into a executable form. The size of
array you have declared initially can be sometimes insufficient and sometimes more
than required. Dynamic memory allocation allows a program to obtain more memory
space, while running or to release space when no space is required.
Although, C language inherently does not has any technique to allocated memory
dynamically, there are 4 library functions under "stdlib.h" for dynamic memory
allocation.
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
Allocates space for an array elements, initializes to zero and then returns a pointer to
calloc() memory
malloc()
The name malloc stands for "memory allocation". The function malloc()reserves a
block of memory of specified size and return a pointer of type voidwhich can be
casted into pointer of any form.
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area
of memory with size of byte size. If the space is insufficient, allocation fails and
returns NULL pointer.
Int ptr;
ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes
respectively and the pointer points to the address of first byte of memory.
calloc()
12
The name calloc stands for "contiguous allocation". The only difference between
malloc() and calloc() is that, malloc() allocates single block of memory whereas
calloc() allocates multiple blocks of memory each of same size and sets all bytes to
zero.
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of nelements. For
example: ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each
of size of float, i.e, 4 bytes.
free()
Dynamically allocated memory with either calloc() or malloc() does not get return
on its own. The programmer must use free() explicitly to release space.
synta
x of
free()
free(p
tr);
This statement cause the space in memory pointer by ptr to be
deallocated. Examples of calloc() and malloc()
Write a C program to find sum of n elements entered by user. To perform this program,
allocate memory dynamically using malloc() function.
//Write a C program to find sum of n elements using malloc() function.
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
}
13
for(i=0;i<n;++i)
{
printf("\nelement %d is at address %u",*(ptr+i),ptr+i);
sum=sum+*(ptr+i);
}
printf("\nSum=%d",sum);
free(ptr);// memory deallocated using free
}
//Write a C program to find sum of n elements using calloc() function.
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
}
for(i=0;i<n;++i)
{
printf("\nelement %d is at address %u",*(ptr+i),ptr+i);
sum=sum+*(ptr+i);
}
printf("\nSum=%d",sum);
free(ptr);// memory deallocated using free
}
realloc()
If the previously allocated memory is insufficient or more than sufficient. Then, you
can change memory size previously allocated using realloc().
Syntax of
realloc()
ptr=realloc(ptr,
newsize);
Here, ptr is reallocated with size
of newsize. #include <stdio.h>
#include <stdlib.h>
14
void main()
{
int *ptr,i,n1,n2;
printf("Enter size : ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
//allocate memory using malloc
printf("Address of previously
allocated memory: \n");
for(i=0;i<n1;++i)
{printf("%u\t",ptr+i); }
printf("\nEnter new size: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);//reallocate
memory using realloc
printf("Address of newly
allocated memory: \n");
for(i=0;i<n2;++i)
{printf("%u\t",ptr+i);}
}
BASIS OF
MALLOC() CALLOC()
COMPARISON
15
BASIS OF
MALLOC() CALLOC()
COMPARISON
memory of size 'size' from the the size of which is equal to num
heap. *size.
STORAGE CLASSES
Every Variable in a program has memory associated with it.
Memory Requirement of Variables is different for different types of
variables. In C, Memory is allocated & released at different places
Term Definition
16
Storage Class determines the location of variable, where it is declared. Variables
declared with auto storage classes are declared inside main memory whereas variables
declared with keyword register are stored inside the CPU Register.
B. Scope ofVariable
Scope of Variable tells compile about the visibility of Variable in the block. Variable
may have Block Scope, Local Scope and External Scope. A scope is the context
within a computer program in which a variable name or other identifier is valid and
can be used, or within which a declaration has effect.
C. Default Initial Value of the Variable
Whenever we declare a Variable in C, garbage value is assigned to the variable.
Garbage Value may be considered as initial value of the variable. C Programming
have different storage classes which has different initial values such as Global
Variable have Initial Value as 0 while the Local auto variable have default initial
garbage value.
D. Lifetime of variable
Lifetime of the variable = Time Of variable Declaration - Time of Variable Destruction
Suppose we have declared variable inside main function then variable will be
destroyed only when the control comes out of the main .i.e end of the program.
Different
Storage
Classes:
AutoStorage
Class
Static Storage
Class
Extern Storage
Class Register
Storage Class
Storage Memory
17
Life time Exists as long as Control remains in the
block
Example
18
printf("\nNum : %d",num);
}
Note :
Two variables are declared in different blocks , so they are treated as different
variables
Storage Memory
19
printf("\nNum : %d",num);
}
Note :
Declaration within the function indicates that the function uses external variable
Functions belonging to same source code , does not require declaration (no need to
write extern) If variable is defined outside the source code , then declaration using
extern keyword is required
Static Storage Class
The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local variables static allows
them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it
causes that variable's scope to be restricted to the file in which it is declared.
In C programming, when static is used on a class data member, it causes only one
copy of that member to be shared by all the objects of its class.
//static storage class
#include <stdio.h>
void display();
void main()
{
display();
display();
display();
}
void display( )
{
static int i = 1;
printf("\n i= %d\n", i);
i++;
}
Output :
i= 1
i= 2
i= 3
20
This is generally used for faster
access.
Syntax
{
register int count;
}
Keyword Register
21
sum = num1 + num2;
}
In the above program we have declared two variables num1,num2. These two
variables are stored in RAM.
Another variable is declared which is stored in register variable.Register variables are
stored in the register of the microprocessor. Thus memory access will be faster than
other variables.
If we try to declare more register variables then it can treat variables asAuto storage
variables as memory of microprocessor is fixed and limited.
22