0% found this document useful (0 votes)
7 views

UNIT IVfunctions notes

Ok

Uploaded by

625fnykp4b
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

UNIT IVfunctions notes

Ok

Uploaded by

625fnykp4b
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Functions

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

There are the following advantages of C functions.

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

There are three aspects of a C function.

o Function declaration A function must be declared globally in a c program to tell the


compiler about the function name, function parameters, and return type.

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.

SN C function aspects Syntax


1 Function return_type function_name (argument list);
declaration
2 Function call function_name (argument_list)

1
3 Function return_type function_name (argument list) {function
definition body;}

The syntax of creating function in c language is given below:

1. return_type function_name(data_type parameter...)


2. {
3. //code to be executed
4. }

Types of Functions

There are two types of functions in C programming:

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:

Example: program based upon function:


//WAP to compute cube of a no. using function.
#include<stdio.h>
void main()
{
int c,n;int cube(int);
printf("Enter a no.");
scanf("%d",&n); c=cube(n);
printf("cube of a no. is=%d",c);
}
int cube(int n)
{

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.

o function with arguments and with return value


o function with arguments and without return value
o function without arguments and with return value
o function without arguments and without return value
1. function with arguments and with return value

//function with arguments and return values


#include<stdio.h>
int add(int,int); //function declaration
void main()
{
int a,b,c;
printf("\n Enter a,b values:");
scanf("%d%d",&a,&b);
c=add(a,b); //function call
printf("\n result=%d\n",c);
}

int add(int x,int y) //function definition


{
int z;
z=x+y;
return z;
}
2. function with arguments and without return value

//function with arguments and without return values


#include<stdio.h>
void add(int,int); //function declaration
void main()
{
int a,b;
printf("\n Enter a,b values:");
scanf("%d%d",&a,&b);
add(a,b); //function call
printf("\n End of main function”);

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

//function without arguments and without return values

#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.

There are 2 types of parameters:


a.) Actual
Parameters.
b.) Formal
Parameters.

a.) Actual Parameters:


These are the parameters which are used in main() function for
function calling. Syntax: <variable name>=<function name><actual
argument>
Example: f=fact(n);

b.) Formal Parameters.


These are the parameters which are used in function defination for processing.
Methods of parameters passing:
1.) Call by
reference.
2.) Call by
value.

Call by value and Call by reference in C


There are two methods to pass the data into the function in C language, i.e., call by value and call
by reference.

call by value and call by reference in c

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.

Consider the following example for the call by reference.


//call by reference

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:

• Reduce unnecessary calling of function.


• Through Recursion one can Solve problems in easy way while its iterative solution is
very big and complex.

7
Disdvantages(limitations)

• Recursive solution is always logical and it is very difficult to trace.(debug and


understand).
• In recursive we must have an if statement somewhere to force the function to return
without the recursive call being executed, otherwise the function will never return.
• Recursion takes a lot of stack space, usually not considerable when the program is small
and running on a PC.
• Recursion uses more processor time.

Examples: programs based upon recursion:


WAP to compute factorial of a no. using Recursion:
//factorial using recursion
#include<stdio.h>

int fact(int); //function declaration

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>

int gcd(int,int); //function declaration

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);
}

3. //to print fibonaci series i.e 0,1,1,2,3,5,8,13,......


#include <stdio.h>
int fibonaci(int );
void main()

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;

return fibonaci(i-1) + fibonaci(i-2);


}
Functions and arrays(passing an array into a function)

//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);
}

float average(int a[],int n)


{
int sum=0,i;
float avg;
for(i=0;i<n;i++)
sum=sum+a[i];
avg= (float)sum/n;
return 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;

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]);

min=minimum(a,n);
max=maximum(a,n);
printf("\n mininum=%d\t maximum=%d",min,max);
}

int minimum(int a[],int n)


{
int i,min=a[0];

for(i=1;i<n;i++)
{
if(a[i]<min)
min=a[i];
}
return min;
}

int maximum(int a[],int n)


{
int i,max=a[0];

for(i=1;i<n;i++)
{
if(a[i]>max)
max=a[i];
}
return max;
}

Dynamic memory allocation

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.

Function Use of Function

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

free() dellocate the previously allocated space

realloc() Change the size of previously allocated space

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

No of blocks Assigns single block of Assigns multiple blocks of the

demanded memory. requested memory.

Syntax void *malloc(size_t size); void *calloc(size_t num, size_t size);

Initialization malloc() doesn't clear and The allocated memory is initialized

initialize the allocated memory. to zero by using calloc().

Manner of Allocation malloc() function allocates calloc() function allocates memory

15
BASIS OF
MALLOC() CALLOC()
COMPARISON

memory of size 'size' from the the size of which is equal to num

heap. *size.

Speed Fast Comparatively slow.

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

Scope Region or Part of Program in which Variable is accessible

Extent Period of time during which memory is associated with variable

Storage Manner in which memory is allocated by the Compiler for Variable


Class Different Storage Classes

Storage class of variable Determines following things


Where the variable is
stored
Scope of Variable
Default
initial
value
Lifetime
of
variable

A. Where the variable is stored:

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

Automatic (Auto) storage class


This is default storage class
All variables declared are of type Auto by default
In order to Explicit declaration of variable use ‗auto‘
keyword auto int num1 ; // Explicit Declaration
Features:

Storage Memory

Scope Local / Block Scope

17
Life time Exists as long as Control remains in the
block

Default initial Garbage


Value

Example

//auto storage class


#include <stdio.h>
void display();
void main()
{
display();
display();
display();
}
void display( )
{
auto int i = 1;
printf("\n i= %d\n", i);
i++;
}
Output :
i= 1
i= 1
i= 1

//auto storage class


#include<stdio.h>
void main()
{

auto int num = 1 ;


{
auto int num = 2;
{
auto int num = 3;
{
printf("\nNum : %d",num);
}
printf("\nNum : %d",num);
}

18
printf("\nNum : %d",num);
}

Note :
Two variables are declared in different blocks , so they are treated as different
variables

External ( extern ) storage class in C Programming

Variables of this storage class are ―Global variables‖


Global Variables are declared outside the function and are accessible to all functions in
the program
Generally , External variables are declared again in the function using
keyword extern In order to Explicit declaration of variable use ‗extern‘
keyword
extern int num1 ; // Explicit Declaration
Features :

Storage Memory

Scope Global / File Scope

Life time Exists as long as variable is running


Retains value within the function

Default initial Value Zero

//auto storage class


#include<stdio.h>
void main()
{

auto int num = 1 ;


{
auto int num = 2;
{
auto int num = 3;
{
printf("\nNum : %d",num);
}
printf("\nNum : %d",num);
}

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

Register Storage Class


register keyword is used to define local
variable. Local variable are stored in
register instead of RAM.
As variable is stored in register, the Maximum size of variable = Maximum Size of
Register unary operator [&] is not associated with it because Value is not stored in
RAM instead it is stored in Register.

20
This is generally used for faster
access.
Syntax
{
register int count;
}

Why we need Register Variable ?


Whenever we declare any variable inside C Program then memory will be randomly
allocated at particular memory location.
We have to keep track of that memory location. We need to access value at that memory
location using ampersand operator/Address Operator i.e (&).
If we store same variable in the register memory then we can access that memory
location directly without using the Address operator.
Register variable will be accessed faster than the normal variable thus increasing the
operation and program execution. Generally we use register variable as Counter.
Note : It is not applicable for arrays, structures or pointers.
Summary of register Storage class

Keyword Register

Storage Location CPU Register

Initial Value Garbage

Life Local to the block in which variable is declared.

Scope Local to the block.

Register storage classes example


//register storage class
#include<stdio.h>
void main()
{
int num1,num2;
register int sum;

printf("\nEnter the Number 1 : ");


scanf("%d",&num1);
printf("\nEnter the Number 2 : ");
scanf("%d",&num2);

21
sum = num1 + num2;

printf("\nSum of Numbers : %d",sum);

}
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

You might also like