0% found this document useful (0 votes)
12 views71 pages

Functions in C

Uploaded by

pethu.tndalu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views71 pages

Functions in C

Uploaded by

pethu.tndalu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 71

FUNCTIONS in C

Top-down design

The programs presented so far are quiet simple.

But when the problem is larger and complex, the

program can be divided in to simpler and

manageable parts known as modules. Each module

can do a well-defined task. This process of dividing

a problem into number of smaller subtasks is

known as top-down design.


Functions - Overview
A function is an independent module or a self-
contained program segment that performs some
specific well-defined task when it is called.
Every C program consists of one or more
functions. One of these functions must be the
main.
The execution of a program always starts and
ends with main, but it can call other functions to
do specific tasks.
A function will do the specific task whenever it
is called from some other portion of the program.
Once the function has carried out its work,
control will be returned to the calling point.
Moreover, information can be passed to a
function through special identifies called
Advantages
1.Complex programs can be divided into number of smaller
components.
2.It avoids redundant programming and supports code
reusability. i.e., when the same set of instructions is accessed
repeatedly in a program, they can be written as a function.
Frequently used functions can be stored in the form of a library
file. If a program requires a particular routine, the
corresponding library function can be called.
3.It is easy to write and debug programs containing functions.
4.Functions can be used to protect the local data. It is the data
available only to the function. It cannot be changed by an
outside function.
Example Program
void main()
{
display( );
printf(“Back to main \n “);
print( );
printf(“Back to main \n “);
}
void display( )
{
printf(“ Now in display \n”);
return ;
}
void print( )
{
printf(“Now in print \n”);
return;
}
Defining a function
The function definition contains the set of
statements needed to complete the task of that
function. It has 2 components:
a)Function header – containing argument
declarations, function name and the return type.
The general form is
return _type name(type1 arg1, type2 arg2, …., typen
argn)
where, return_type - data type of value
returned by the function.(void – when there is no
return value)
name-function name, arg1, …., argn
List of arguments or parameters.
type1,…, typen - data types of the arguments.
The arguments declared in the function definition are
b)Function body - consists of the set of
statements that defines the action to be done
by the function. It may contain one or more
return statements for returning a value to the
calling function. But an empty return
statement is optional, if the function doesn’t
return a value.
Types of Function Designs
A user-defined function may fall into any of
the following categories.
a.Functions with no arguments and no return
values.
b.Functions with arguments and no return
values
c.Functions with arguments and return
values.
a. No arguments and no return values
When the function has no arguments, it doesn’t
receive anything from the calling function.
When the function does not return a value, it is
not sending anything to the calling function.
Hence there is no data transfer between calling
and called function.
Example
#include<stdio.h>
void print(int x)
{
printf(“%d \n”,x);
return;
}
void main( )
{
int a=10;
print (5);
print (a);
}
Output
5
10
Example
#include<stdio.h>
int sqr(int x)
{
return(x * x); /* returns
the square of x */
}
void main()
{
int a = 5, b;
b = sqr(a);
printf(“%d”,b);
}
Output 25
Calling a function
A function can be called by specifying its name,
list of arguments enclosed in parenthesis and
separated by commas and terminated by a
semicolon. Use empty parenthesis, when there
are no arguments.
The general form is
name(arg1,arg2,….arg n);
The function call can be a part of an expression,
if it returns a value. But a function not returning
a value should not be used in expressions; they
must be an independent statement.
Example
#include<stdio.h>
int sum(int x, int y)
{
return(x+y);
}
void main( )
{
int a = 1,b = 2,c = -3,d = 4;
res = sum( a, b) / sum( c , d ); /* function calls as
part of an
expression */
printf(“%d”,res);}
The arguments appearing in the function
calling statement are called as actual
arguments and the arguments appearing in
the function header are known as formal
arguments. The actual and formal parameters
must match in number, type and order. The
values of actual arguments are assigned to
the formal argument on a one to one basis.
But the names of actual and formal argument
may differ.
Function Declaration
When the function call occurs before the function
definition, the compiler must be informed in prior
about the function. The function declaration is
used for this purpose. They are written at the
beginning before the user defined functions.
A function declaration contains only a function
header but no code. The declaration consists of 3
parts, as like function headers.
 a. Return type (void – if no return value)
 b. Function name
 c. Name (optional ) and type (essential)
of formal parameters.
The general form is
 return-type name(type1 arg1,…..type n
Parameter Passing Techniques
There are 2 ways in which parameters can be
passed to a function.
a. Call by value.
b. Call by reference.

a. Call by value
In this method, the value of the actual
arguments in the calling function is copied
into corresponding formal arguments of the
called function.
Therefore, the changes made to the formal
arguments have no effect on the values of
actual arguments
Advantages
It protects the original data in the calling
function, since the changes inside the called
function will not be reflected over it.
It allows even expressions as actual arguments
rather than a single variable.
Disadvantage
1)It is a one- way transfer of information from
the calling function to called function.
Information cannot be transferred back
through arguments.
Call by reference / call by address:
In this method, the addresses of the actual
arguments are copied into the formal arguments.
Any reference to a formal parameter is same as a
reference to the actual parameter in the calling
function.
Thus, when the called function changes a value,
it actually changes the variable in the calling
function.
To pass an address, the address operator (&) is
used. A variable that holds this address is known
as pointer variable. It is represented using the
dereferencing operator (*).
Recursion
Recursion is a process in which a function calls
itself repeatedly till some specified condition is
satisfied.

Two things are essential for solving a problem


using recursion.
1.The problem must be written in a recursive
form, so that, every recursive call must either
solve a part of the problem or reduce the size
of the problem.
2.The problem statement must include a
stopping condition
#include<stdio.h>
int fact(int);
void main( )
{
int n;
printf(“Enter the no \n”);
scanf(“%d”,&n);
printf(“factorial is %d”, fact (n));
}
int fact(int n)
{
if (n = = 0)
return(1);
else
return( n * fact (n-1));
}
#include <stdio.h>
void towers(int, char, char, char);
int main()
{
int n;
printf("Enter the number of disks :
(greater than 0");
scanf("%d", &n);
printf("The sequence of moves involved in
the Tower of Hanoi are :\n");
towers(n, 'A', 'C', 'B');
return 0;
void towers(int num, char source, char dest,
char inter)
{
if (num == 1)
num=1,s=A, des
{
printf("\n Move disk 1 from %c to %c",
source, dest);
return;
}
towers(num - 1, source, inter, dest);
printf("\n Move disk %d from %c to %c",
num, source, dest);
towers(num - 1, inter, dest, source); } }
STORAGE CLASSES IN
C
Storage Classes
In C, there are two ways to characterize variables.
a.By data type
The data type refers to the type of information
represented by a variable. e.g., int, float etc.,
b.By storage classes
The storage class provides information about their
location and visibility.
The storage class of C variables defines two
characteristics, namely,
Spatial information :It tells where a variable is defined
i.e., in which part of a program, a variable can be
referred and is actually available for use (active).This is
also known as Scope or visibility.
Temporal information:It tells when a variable is alive.
When memory is allocated for a variable, it is said to be
Types of Storage Classes
Automatic Variables
Automatic variables are always declared inside a
function or a block and they are local to that function
or block.
By default, any variable declared without a storage
class specifier, will be treated as auto variables.
Hence, even the keyword auto is not required. All the
variables used by us so far are auto variables.
 e.g., int x; /* denotes an auto variable */
 auto float y;
Automatic Variables
The characteristics of auto variables are given
below.
Spatial limitation (Scope) Local. It is visible
inside the function where it is declared and is
undefined in other places.

Temporal limitation (Lifetime):It is alive inside


a function or block when it is running. When the
function ends, the variable will not be valid and
should not be accessed.

Initialization :Uninitialized auto variables contain


garbage values and hence, must be properly
initialized.
Automatic Variables
Automatic Variables
Static Variables
A static variable can be defined inside a function or a
block and they are local to that function or block. It
cannot be accessed from outside the function.

But unlike the auto variables, static variables retain


their values throughout the life of that program.
Hence, if a function is exited and re-entered again,
the static variables retain their values.
static int a;
Static Variables
The characteristics of static variables are given
below.
Spatial limitation (Scope) Local. It is visible
inside the function where it is declared and is
undefined in other places.

Temporal limitation (Lifetime):It is alive for the


whole program. It is born when the program starts
running and dies when it stops.
Initialization :Static variables can be initialized
only once. During the next time when the function
is called, the previous values will persist.
Uninitialized static variables will be automatically
initialized to zero.
Static Variables
#include <stdio.h>
void fun( ); /* Function prototype */
void main( )
{
int i;
for (i = 0; i<3; i++)
fun( );
}
void fun( )
{
static int a=0;/* Initialization works only
once */
a++;
printf("a = %d \n",a);
Static Variables & Automatic Variable
#include <stdio.h>
void fun( );
void main( )
{
int count;
for (count = 0; count < 3; count++)
{
printf("At iteration %d: ", count);
fun();
}
}
void fun(void)
{
static int x = 0;
int y = 0;
x++;
y++;
printf("x = %d, y = %d\n", x, y);
}
Output
At iteration 0: x = 1, y = 1
At iteration 1: x = 2, y = 1
External Variables
They are also known as global variables. Extern
variables are alive and active throughout the
program. They are declared outside all the
functions. Hence, they can be accessed from
anywhere in the program.
The characteristics of external variables are given
below.
Spatial limitation (Scope) Global. It is
accessible from anywhere inside the program.
Temporal limitation (Lifetime):It is alive for the
whole program. It is born when the program starts
running and dies when it stops.
Initialization :Exernal variables can be
initialized only once. During the next time when the
External Variables
int count;
void fun1( )
{ count = 0; /* Global variable */
……………..
}
void fun2( )
{
int count = 10;
count++; /* Local variable */
}
void main( )
{
……………..
}
External Variables
int count;
void fun1( )
{ count = 0; /* Global variable */
……………..
}
void fun2( )
{
int count = 10;
count++; /* Local variable */
}
void main( )
{
……………..
}
External Variables
void fun1( )
{ count = 0; /* count – Undefined at this
point */
……………..
}
int count = 0;
void main( )
{
count++; /* OK */
……………..
}

In the above example, the usage of variable count in the function


fun1( ) leads to error message. To avoid this, the variable may be
declared as extern which tells the compiler that count is defined
somewhere else in the program.
External Variables
void fun1( )
{ extern int count; /* External
declaration */
……………..
}
int count = 0;
void main( )
{
count++; /* OK */
……………..
}
Register Variables
A register variable tells the compiler to use a CPU
register for the variable instead of a memory
location.The scope and lifetime of Register variables are
same as auto variables.
register int a;
Advantages
a.The time taken for accessing a CPU register is less
than the time required for accessing a memory location.
Hence they are more efficient.
b.Frequently accessed variables can be stored in
registers.
Disadvantages
a.Only few numbers of Registers are available with CPU
and the compiler uses all of them for running the
program efficiently. Hence most of the time compiler
will not allocate registers for our request.
Structures in C
A structure is a collection of related elements of
different data type, grouped under a single name.
The individual elements of a structure are known
as its members. The individual members of a
structure can be ordinary variables, pointers,
arrays or other structures.
Defining a structure
A structure may be defined as follows.
struct tag
{
type1 member1;
type2 member2;
……………
typem member m;
};
where
struct - keyword
tag - name of the structure
member1,……,member m - individual
members.
type1,………,typem - data types of
members.
Structures
Structure definition doesn’t tell the compiler to
reserve any space in the memory. Only when
structure variables are declared, space will be
reserved in the memory. Structure-type
variables can be declared as follows.
struct tag Variable1,Variable 2,
……..Variable n;
Example
struct employee
{
int empno; Structure definition
char name[10];
float salary;
}
Initialization
Structure variables can be initialized when
they are declared. The rules for structure
variables initialization are same as the rules of
array initialization. The values must be
enclosed in braces and separated by commas.
The general form is.

struct tag variable ={ Value 1,Value


2,..Value m};

Example

struct employee emp1={1,”siva”,


15000};
#include<stdio.h>
void main()
{
struct stud
{
int rollno;
char name[10];
int age;
};
struct stud
s1={111,”swapna”,20};
printf(“Address of rollno = %u \n”,
&s1.rollno);
printf(“Address of name= %u \n”,
s1.name);
printf(“Address of age = %u \n”,&s1.age);
printf(“Total size required = %d”,
sizeof(s1));
}
Assigning a Structure variable to
another
The values of structure variables can be
assigned to another structure variable of the
same type using the assignment operator. It may
be copying the individual elements one–by –one
or all at once. Also two structure variables of
same type can be compared with each other.
# include <string.h>
# include <stdio.h>
void main()
{
struct stud
{
int rollno;
char name[10];
int age;
};
struct stud s1={111,”swapna”,20};
struct stud s2,s3;
s2.rollno=s1.rollno; /* copying members one
by one */
strcpy(s2.name,s1.name);
s2.age = s1.age;
s3 = s1; /* copying all at
once */
printf (“%d%s
%d”,s1.rollno,s1.name,s1.age);
printf (“%d%s
%d”,s2.rollno,s2.name,s2.age);
printf (“%d%s
%d”,s3.rollno,s3.name,s3.age);
if (s1= =s2) /* Comparing
structure variables */
printf(“s1and s2 are same”);
else
printf(“s1and s2 are not
Nested Structures
When a structure includes another structure
variable as its member, it is called as a nested
structure. In such a situation, the declaration
of the embedded structure must appear before
the declaration of the outer structure.
void main()
{
struct address
{
char street[10],city[20];
int pin;
};
struct stud /* structure address declared
before this */
{
int rollno;
char name[10];
struct address addr;
};
struct stud s = {100,”priya”,”new
road”,”salem”,628091};
printf (“%d %s\n”, s.rollno,s.name);
printf (“%s %s %d\n”,
s.addr.street,s.addr.city,s.addr.pin);
}
Array of Structures
It is also possible to define an array of structure i.e., an
array in which each element is a structure.
Example
void main()
{
struct employee
{
int empno;
char name[10];
};
struct employee emp[5]; /* array of
structures */
int i;
printf (“enter 5 employee numbers and
names”);
for(i=0;i<4;i++) {
scanf (“%d %s”, emp[i].empno,
Passing Structures to functions
A Structure can be passed to a function in 3
ways:
a. passing individual members to a function
b. passing the whole structure to a function
c. passing the address of a structure or a
member to a function
Passing individual members
Individual structure members can be passed as
arguments to a function. We are actually passing the
value of that member to the function. The arguments are
then treated independently as ordinary variables.

Example
#include <stdio.h>
void display(int,float);
void main() {
struct account
{
int accno;
float bal;
};
struct account a = {100,25000};
display(a.accno, a.bal); }
void display(int no, float balance) {
printf(“Account no :%d Balance : %f ”, no,
balance); }
b. Passing the entire structure
When a structure is passed to a function, the
transfer is by value. i.e., the values will be copied
in a local structure and if any of the structure
variables are altered inside the function, the
changes will not be recognized in the calling
function. If we need the changes, the entire
structure has to be returned from the function.
Also we have to specify the type of the formal
parameters and return type.
#include <stdio.h>
void display (struct distance);
struct distance sum(struct distance, struct
distance);
void main( ) {
struct distance
{
int feet;
int inch;
}d1, d2, d3;
printf(“Enter 2 distances: feet & inch \n”);
scanf(“%d %d”,&d1.feet, d1.inch);
scanf(“%d %d”,&d2.feet, d2.inch);
printf(“Distance l is”)
display(d1); /* pass the structure
variable d1 */
printf(“Distance 2 is”);
display(d2); /* pass the structure
variable d2 */
d3 = sum(d1,d2);
printf(“Sum is \n”);
display(d3);
}
void display(struct distance d)
{
printf(“Feet : %d Inches %d \n”, d.feet, d.inch);
}
struct distance sum(struct distance dist1, struct
distance dist2)
{
struct distance dist3;
dist3.feet = dist1.feet + dist2.feet;
dist3.inch = dist1.inch + dist2.inch;
return dist3;
}
c. Passing the address of a structure
The address of a structure variable or member can
be passed as arguments using pointers. A structure
passed in this manner is said to be passed by
reference. Hence, if any of the structure members
are altered within the function, the changes will be
recognized in the calling function. Using the
pointer to the structure, the members of the
structure can be accessed with ->operator
#include <stdio.h>
struct distance
{
int feet;
int inch;
};
void increment(struct distance *);
void main( )
{
struct distance d = {10,1};
printf(“Before increment : %d %d”, d.feet, d.inch);
increment (&d);
printf(“After increment :%d %d”, d.feet, d.inch);
}
void increment(struct distance *dist)
{
(dist->feet)++;
(dist->inch)++;
}
Self-referential structures
If a member of a structure is a pointer to itself,
then it is said to be self-referential structures. Self
referential structures are very useful in
applications that involve linked data structures.
The general form is
struct tag
{
member 1;
member 2;
…………
struct tag *ptrname; /* pointer to itself */
};
where

You might also like