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

UNIT4

Uploaded by

manasa rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

UNIT4

Uploaded by

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

UNIT4

UNIT 4

USER DEFINED FUNCTIONS


A function is a self-contained block of code that performs a particular task.
C functions can be classified into two categories, namely library functions and
user defined functions. The main difference between these two is that library
functions are not required to be written by us whereas a user defined function has
to be developed by the user at the time of writing a program.

Need For User-Defined functions:


While it is possible to write any program with only main () function, it
leads to a number of problems:
1. The program may become too large and complex so that debugging becomes
difficult.
2. Testing & maintenance becomes difficult.
3. For programs, which involve several repetitions of the same task, main()
function grows lengthy and leads to confusion.
4. More comment lines are required to be written to make the program
understandable.
To overcome all these difficulties, the program can be divided into a
number of user-defined functions & then each of them may be independently
coded and later combined into a single unit.
Advantages:
1. It facilitates top-down modular programming.
2. The length of a source program can be reduced by using functions at
appropriate places.
3. It is easy to locate and isolate a faulty function for further investigations.
4. A function may be used by many other programs

1
UNIT4

ELEMENTS OF USER-DEFINED FUNCTIONS


The three elements that are related to functions are:
1.Function definition
2.Function call
3.Function declaration
 The function definition is an independent program module that is specially
written to implement the requirements of the function.
 In order to use this function we need to invoke it at a required place in the
program. This is known as the function call.
 The program that calls the 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.

DEFINITION OF FUNCTIONS
Defining a function refers to the process of writing the actual code of a
function that performs a specific and identifiable task, such as computing the
factorial of a given number. A function can be defined before or after the main
program. It can be even defined in another file.
A function definition, also known as function implementation includes two
parts, namely,
 Function header
 Function body.
The general format of a function definition is
Return_type function_name (Argument list with declaration) Function Header
{
local variable declaration;
executable statements;
....................
return statement;
} Function Body

2
UNIT4

The Function Header consists of three parts Return type, Function name and
Argument list with declaration.
i) Return type (also known as function type): It denotes the data type of the
result returned by the function. Return type can be any normal data type
such as int , float, char or void. If the return data type is omitted in the
declaration then the function is assumed to return integer data type. Void
data type is used when the function does not return any value to the
calling function.

ii) Function Name: Function name can be any valid C identifier that is used
to uniquely identify the user defined function.

iii) Argument list with declaration (also known as formal parameters): The
argument list indicates the set of variables that will receive the values
sent by the calling function. Like every other variables, the argument list
should be declared along with their data type.
The Function Body contains the declaration and statements necessary for
performing the required task. The body is enclosed in flower bracket and has
three parts in the order given below.
i). Local variable declaration that specify the variables needed by the function.
These variables are local to the function and are not available outside this
function.
ii). Function statements are the executable statements that are required to
perform the task.
iii). A return statement is used to return the resultant value of the function
to the calling program.
For example consider the following function that is used to find the sum of
two numbers.

3
UNIT4

Return type Function Name Argument list with declaration

int Sum( int a, int b) Function Header


{
int s;
s = a+b; Local variable Declaration
return (s) ;
} Executable Statement

Returned value

Body of the function

This function is named as Sum. It takes two integer arguments a, b, and


returns an integer value. There is a local integer variable s that temporarily holds
the sum of two input arguments a & b. Finally the return statement will send
back the value of s to the calling function.

FUNCTION PROTOTYPE
Like variables, all functions in C program must be declared, before they are
invoked. The declaration of a function before using it, is called as a function
prototype. The prototype is used to identify the type of values returned to calling
subprogram and helps the compiler to generate the correct code for the return
data. Prototype can also identify the no.of arguments and the sequence in which
they are used by the function.
The general format of function prototype is as follows:
return_typeFunction_Name (Type1, Type2, ....); or
return_typeFunction_Name( Type1 Arg1, Type2 Arg2, ....);
For example, a function that is used to add two integer numbers and return their
sum can have a typical prototype as
int sum(int, int);
4
UNIT4

OR
int sum( int a, int b);
The argument types in the function declaration must match the types of
parameters in function definition, in number and order. The parameters names do
not need to be same in the prototype declaration and the function definition.
FUNCTION CALL
A function call establishes the link between the called function and the
calling subprogram. A function can be called by specifying its name followed by
a list of actual parameters enclosed in parentheses. General syntax of function
call is as follows.
Variable =Function_Name( arg1, arg2, .....);
When the compiler encounters a function call, the values of actual parameters
are copied to the formal parameters and the control is transferred from the calling
sub program to the called function.

FORMAL AND ACTUAL PARAMETERS


Parameters used in function header during its definition are referred to as
formal parameters or dummy arguments. The formal parameters will receive
their values from the calling function during the function call.
A function call is made by first specifying the name of the function along
with some parameters included inside parentheses. These parameters are known
as actual parameters. Actual parameter represents the values that are passed to
the function during the function call. Actual parameters can be variable names,
constants or expression.

Following points are considered while defining the formal and actual parameters.
 The no. of formal parameters should be equal to the no.of actual arguments.
 The data types as well as the order of creation of formal parameters and
actual arguments should be same.
 The formal parameters and actual arguments can have same or different
names.

5
UNIT4

 The formal parameter must be always a variable where as the actual


parameter can be variable, constant or expression.

Return STATEMENT
The return statement is used to send back values from the called function to
the calling function. A function can return none or at most one value per call. The
general form of return statement is,
return;
Or
return (expression);
The first return statement does not return any value to the calling function.
It is used to exit from the function and return the control to the point from where
it is called. The second form returns a single value of the expression to the calling
function.

GLOBAL AND LOCAL VARIABLES


Variables declared inside a block or functions are referred to as local
variables. The scope of the local variable is confined only to the function or the
block in which it has been defined. Same variable name may be given in another
function and each variable, will be treated as a different entity.
Variables declared outside the main or any other function are referred to as
global variables. If the global variables are declared in the beginning of the
program, then they are available throughout the program and in every block of
the program. However if the global variables are declared after one or more
functions then they are not available to the functions defined above them but are
available to all the functions that are defined below them.

Example: Program to find the sum of two natural numbers.

#include<stdio.h>
6
UNIT4

void main()
{
int m, n, s1;
int sum (int, int); Function Prototype

printf(“Enter two numbers:”);


scanf(“%d %d”, &m, &n); Actual Parameters

s1 = sum(m, n); Function Call

printf(“Sum of two numbers = %d”, s1);


}
Formal Parameters

int sum ( int a, int b)


{
int s; Local Variable
s = a + b;
return(s); returns the value of s to the calling function
}

CATEGORY OF FUNCTIONS
A function, depending on whether arguments are present or not and
whether a value is returned or not, may belong to one of the following categories:
1. Function with no arguments and no return values.
2. Function with no arguments and one return value.
3. Function with arguments and no return value
4. Function with arguments and one return value.

FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUE


In this type of function there is no exchange of data between the calling and
called function. The called function has no arguments and does not receive any
data from the calling function. Also since these functions do not return any value,
the return type of these functions is “void”. The keyword “return” can be omitted

7
UNIT4

from the body of the function as it does not return any value. Finally as these
functions do not return any value, they cannot be used in an expression, instead
they can be only used as an independent statement in the calling function.
Example:
#include<stdio.h>
main()
{ void printline(); /* function prototype */
printline(); /* function call */
printf(“Welcome to c”);
printline();
}
void printline() /* function definition */
{ printf(“--------------------------------------------\n”);
}
In the above example the calling function “main()” calls the function
“printline()”. All the function calls are independent statements and there is no
exchange of data between the called function and calling function.

FUNCTION WITH NO ARGUMENTS BUT RETURNS A VALUE


There could be occasions where we may need to design functions that may
not take any arguments but returns a value to the calling function. In this example
program m and n are declared as global variables and hence it is accessible by all
the functions. Therefore no any arguments are passed but value returned from the
function.
Example:
#include<stdio.h>
Int m,n; //global variables
void main()
{
int s1;
int sum ( ); //Function Prototype
printf(“Enter two numbers:”);
scanf(“%d %d”, &m, &n);
8
UNIT4

s1=sum(); //Function Call

printf(“Sum of two numbers = %d”, s1);


}

int sum ( )
{
int s; // Local Variable
s = m+n;
return(s);
}

FUNCTION WITH ARGUMENTS AND NO RETURN VALUE


In this category of functions the called function will receive arguments or
values from the calling function but will not return any value to the calling
function. Since the function does not return any value, the return type of this
function is always void and the keyword return can be omitted from the body of
the function.
When calling these type of functions the actual arguments must match in
number type and order with the formal parameters. During the call the actual
arguments value will be copied to the formal arguments.
Example:
#include<stdio.h>
Void main()
{
int m, n, s1;
void sum (int, int); //Function Prototype
printf(“Enter two numbers:”);
scanf(“%d %d”, &m, &n);

sum(m, n); //Function Call

9
UNIT4

void sum ( int a, int b)


{
int s; //Local Variable
s = a + b;
printf(“Sum of two numbers = %d”, s);
}

FUNCTION WITH ARGUMENTS AND A RETURN VALUE


In this category the called function receives the input values from the
calling function, performs a predefined task and returns the computed result to
the calling function. Since these functions return value to the calling function, the
return type cannot be void. The return type should be the data type of the value
being returned to the calling function. There must be a return statement in the
body of these functions to return the resulting value to the calling function.
When calling, the actual arguments must match in number type and order
with the formal parameters.
Example:
#include<stdio.h>
Void main()
{
int m, n, s1;
int sum (int, int); //Function Prototype
printf(“Enter two numbers:”);
scanf(“%d %d”, &m, &n);

s1 = sum(m, n); //Function Call

printf(“Sum of two numbers = %d”, s1);


}

int sum ( int a, int b)


{
int s; Local Variable
s = a + b;
10
UNIT4

return(s);
}

NESTING OF FUNCTIONS

C permits nesting of functions. main() can call function1( ), which calls


function2( ), which calls function3( ),..... and so on.

main( )
{
-------
--------
function1( );
--------
}
function1( )
{
------
function2( );
--------
}
function3( )
{
------
------
}

RECURSION
A function that calls itself directly or indirectly again and again until some specified
condition is satisfied, is termed as a recursive function. Hence the function performs its
specified task by repeatedly calling itself. A recursive function contains a terminating
condition that is used to stop the recursion.
Example: Program to find the factorial of a number using recursion.
#include<stdio.h>
int FACT ( int);
11
UNIT4

void main()
{ int n , fact;
printf(“Enter a number:”);
scanf(“%d”, &n);
fact = FACT(n);
printf(“The factorial of %d is %d”, n, fact);
}
int FACT( int n)
{ if(n == 1)
return (1);
else
return ( n * FACT (n-1));
}

STRUCTURES AND UNIONS


STRUCTURE
Structure is a collection of related data items of different data types, grouped and
treated as a single unit.

DEFINING A STRUCTURE
The definition of structure starts with a keyword struct, followed by the name of the
structure. All the members of the structure along with their data types are then grouped
together in a flower bracket. Finally, a semicolon is used to terminate the structure definition.
The general format of a structure definition is as follows,
structTag_name
{ data-type Member1;
data-type Member2;
......
data-typeMembern;
};
● Tag_name is the name given to structure during its definition. It identifies the type of
structure with its members. Tag name can be used to subsequently declare structure
variables.
● The Members refers to the data elements of the structure. The list of all structure
members is called as a template. The template informs the compiler about the amount
of memory to reserve for each of structure variable.
For example: A structure to hold students information can be defined as follows,
12
UNIT4

struct student
{ int regno;
char name[15];
float fees;
};

DECLARING A STRUCTURE VARIABLE


The definition of the structure does not create any memory space in which values can
be stored; this is achieved by declaring the structure. The syntax of structure declaration is as
follows,
structTag_name Variable-list;
The declaration starts with a keyword struct followed by the tag name given to the
structure during tits definition. This is followed by the list of variable names separated by
comma and finally a terminating semicolon.
For example: If a structure to hold student information is defined as follows,
struct student
{ int regno;
char name[15];
float fees;
};

The variable declaration for the above structure can be done as,
struct student S1, S2;

This declaration creates two structure variables S1, and S2 of type student.

It is also possible to combine the structure definition and declaration in one statement as
shown below.
struct student
{ int regno;
char name[15];
float fees;
} S1, S2;
Finally the structure declaration can also be done without using the tag name as follows.
struct
{ intregno;
char name[15];

13
UNIT4

float fees;
} S1, S2;

Rules to be followed while defining a structure:


1. The structure definition must begin with a keyword struct.
2. A tag name is use to identify the type of structure with its members.
3. Each member is declared independently with its name and data type.
4. The members are enclosed in a flower bracket.
5. The definition is terminated with a semicolon.

ACCESSING STRUCTURE MEMBERS


The members of the structure can be accessed or referred using member operator. The
member operator is also known as ‘dot operator’ or ‘period operator’. It is represented as a
period ( . ). Syntax to access members of the structure is as follows.
structure_variable_name .member_name
The member operator establishes a link between the member and the structure
variable. It is also called as ‘dot operator’ or a ‘period operator’.

Example: if a structure to hold student information is defined as,


struct student
{ intregno;
char name[15];
float fees;
} S1, S2;
To refer the membersregno and name we can use the member operator in the following
manner.
S1.regno, S1.name and S2.regno, S2.name.
For example: The values can be given using scanf as,
scanf(“%s”, S1.name);
scanf(“%d”, &S1.regno);

STRUCTURE INITIALIZATION
Structures can be initialized at compile time by assigning a set of values to each
member of the structure variable during its declaration. The values must be separated by a
comma and enclosed in a flower bracket. As shown below.
For example, the values can be initialized to the above defined structure student as,
struct student S1 = {1234,”Gopal”, 26000 };
14
UNIT4

struct student S2 = { 1235, “Ravi”, 45000 };


We can combine the definition, declaration and initialization in a single statement as,
struct student
{ int regno;
char name[20];
char class[5];
char sec[4];
} S1 = { 1212, “Suman”, “I b.com”,”CA”};

Rules for initializing a structure:


1. Individual members of the structure cannot be initialized inside the structure template.
2. The order of values enclosed in braces must match the order of members in the
structure definition.
3. Partial initialization of members is possible. This is done by initializing the first few
members and leaving the remaining blank.
4. The un-initialized members should be only at the end of the list.
5. Un-initialized members are assigned the default values, zero in case of integer and
float, ‘\0’ in case of characters and string.

COPYING AND COMPARING STRUCTURE VARIABLES


Two variables of the same structure type can be copied the same way as ordinary
variables. If person1 and person2 belong to the same structure, then the following statement
is valid:
person1 = person2;
person2 = person1;
However, the relational operators such as
person1 == person2;
person1 != person2;
are not permitted. C does not permit any logical operations on structure variables. In case we
need to compare them, we may do so by comparing members individually.
For example:
struct Book
{ char title[20];
int pages;
float price;
15
UNIT4

};

void main()
{
inti;
struct Book B1 = { “Let Us C”, 550, 220.00};
struct Book B2 = {“Let Us C”, 700, 275.00 };
struct Book B3 = B1;
if ( (B1.pages = = B3.pages) && (B1.price == B3.price) )
printf(“ B1 and B3 are same \n”);
else
printf(“B1 and B3 are different \n”);
}

ARRAYS OF STRUCTURES
An array is defined with structure as its data type is called as array of structure. Here
each element of the array is structure. Array of structures are used whenever the same
structure is to be applied to a group of people, items or applications. For example to maintain
the details of all students in a college, we can create a array of structure as follows,
struct student Std[100];
defines an array called std, that contains 100 elements. Each element is defined to be of the
type struct student. Consider the following declaration:

struct Marks
{ int m1;
int m2;
int m3;
};
Marks student[3] = { { 45, 68, 77 }, { 64, 38, 46 }, {57, 36, 71} };

This declares the student as an array of three elements student[0], student[1], and student [2]
and initializes their members as follows: Table of Records
student[0].m1 = 45; m1 m2 m3
student[0].m2 =68;
Student[0]
.......
Student[1]
.......
Student[2]
student[2].m3 = 71;
16
UNIT4

ARRAYS WITHIN STRUCTURES


C permits the use of arrays as structure members. We have already used array of
characters inside a structure. Similarly, we can use single-dimensional or multidimensional
arrays of type int or float.
For example, the structure declaration is valid:
struct Marks
{ int number;
char name[20];
float subject[3];
} student[2];

Here, the member subject contains three elements subject[0], subject[1] and subject[2].
These elements can be accessed using appropriate subscripts. For example, the name
Student[1].subject[2];
Would refer to the marks obtained in the third subject by the second student.
Example program:

#include <stdio.h>
struct student
{
Char sname[20];
int marks[3];
}s1;

void main()
{
printf("\nEnter the Name of Student : ");
gets(s1.sname);

printf("\nEnter the Marks in Subject 1 : ");


scanf("%d",&s1.marks[0]);
printf("\nEnter the Marks in Subject 2 : ");
scanf("%d",&s1.marks[1]);
printf("\nEnter the Marks in Subject 3 : ");
scanf("%d",&s1.marks[2]);
17
UNIT4

printf("\n ---- Student Details -------- ");


printf("\n Name of Student : %s",s1.sname);
printf("\n Marks in Subject 1 : %d",s1.marks[0]);
printf("\n Marks in Subject 2 : %d",s1.marks[1]);
printf("\n Marks in Subject 3 : %d",s1.marks[2]);
}

STRUCTURES WITHIN STRUCTURES


A structure within a structure is called nested structure or embedded structure. A
nested structure is embedded within another structure as its members. There are two ways of
defining a embedded structure.
1. A structure may be completely defined within the other structure.
For example:
struct student
{
intregno;
char name[20];
struct date
{ int day;
int month;
int year;
} dob;
};

2. There may be separate structures. The embedded structure must be defined first
and used as a member of the outer structure. For example,
struct date
{ int day;
int month;
int year;
};

struct student
{ intregno;
char name[20];
struct date dob;

18
UNIT4

};
Note: The embedded structure ’date’ (in case 2) must be defined before the outer structure
‘Student’.
An innermost member in a nested structure can be accessed by chaining all the
concerned structure variable from outer-most to inner-most with the member using dot
operator. For example, to access day month and year from a nested structure we can use the
dot operator as follows;
struct student Mystudent;
/* Accessing the innermost members */
Mystudent.doj.day = 15;
Mystudent.doj.month = 6;
Mystudent.doj.year = 2005;

Example: Program for nested structure


struct Address
{ char city[20];
longint phone; OUTPUT:
longint pin; The details of employee E1
is :
};
Name : Prakash
struct Employee City : Mangalore
{ charename[20]; Phone. No : 9845126389
struct Address add; Pincode : 575028
Employee No : 1005
intempno;
};
void main()
{ struct Employee E1 = { “Prakash”, “Mangalore”, 9845126389, 575028, 1005};
printf(“ The details of employee E1 is: \n”);
printf(“Name : %s \n”, E1.ename);
printf(“City : %s \n”, E1.add.city);
printf(“Phone. No : %ld \n”, E1.add.phone);
printf(“Pincode : %ld \n”, E1.add.pin);
printf(“Employee No : %d \n”, E1.empno);
}
In the above program, the structure Address is nested within the structure Employee.
To access the elements of structure Address we need to use the dot operator twice.
For example: To access the member city, we have written,
E1.add.city

19
UNIT4

STRUCTURES AND FUNCTIONS


Like ordinary variable, a structure variable can also be passed to and returned from a
function as parameters.
When the structure is passed as an actual parameter, any changes to the structure
members will not be effected to the members in the calling function. This means that we will
have to return the entire structure back to the calling function. This method of passing an
entire structure as an argument to the called function may not be supported by all compilers.

For example:
struct Book
{ char title[20];
float price;
int pages;
};
struct Book Update (struct book); /* Function Prototype */

void main()
{ struct Bok B1={ “Let Us C”, 220.00, 550 };
printf(“The details of book B1 before reprinting\n”);
printf(“Name : %s Price: %.2f Pages: %d\n”,B1.title, B1.price, B1.pages);
B1 = Update(B1); /* Function Call – Passing structure B1 as parameter */
printf(“\nThe details of book B1 after reprinting\n”);
printf(“Name : %s Price: %.2f Pages: %d\n”,B1.title, B1.price, B1.pages);
}

struct Book Update( struct Book B) /* Function Definition */


{ B.price = B.price + B.price*0.1;
B.pages = 700;
return (B);
}

OUTPUT:

The details of book B1 before reprinting


Name : Let Us C Price: 220.00 Pages: 550

The details of book B1 after reprinting


Name : Let Us C Price: 242.00 Pages: 700

20
UNIT4

DIFFERENCE BETWEEN STRUCTURE AND AN ARRAY

Structure Array
1. An array is a collection of
1. Structure is a collection of related
related elements of same data
elements of different data types.
type.

2. Structures uses dot operator to 2. Array uses index or subscript


access its members. to access its elements.

3. In structure there is no such thing


3. Array can be one dimensional
as one dimensional or multi
or multi dimensional.
dimensional

4. Nested structures are possible. 4. Nested array is not possible.

5. Two structure variables can be 5. Assigning one array variable


assigned to simultaneously copy to another will not copy the
the contents of individual members contents of one array onto
within the structures. another.

6. Structures are user-defined data 6. Array behaves like a built in


types. data type.

Unions
A union is a mutually exclusive collection of elements of which only one should be
used at any given instance of time.
The concept of unions is borrowed from structures and therefore follows the same
syntax as structures. The difference between structures and unions is in terms of storage. In
structures each member has its own storage location; where as all the members of a union
use the same location. So it can handle only one member at a time.
General form of Union definition is as follows:
unionTag_Name
{ data_type Member1;
data_type Member2;
21
UNIT4

......
data_typeMembern;
};
Here union is a keyword, Tag_name is the name that identifies union of this type and
Member1, Member2, ...,Membern are individual members of the union.

Syntax for declaring the variable is as follows,

unionTag_NameVariable_list;

where variable list is a list of any valid identifier that are separated by comma.
For example:
union Item
{ int m;
Float p;
char c;
};
This defines a union template ‘Item’, to declare the variable of this type we can use the
following statement.

Example: union Item purchased;

Here a variable of type union having a name ‘purchased’ is created. Union contains
three member of different data type; however only one can exists at a time. The compiler
will allocate a piece of memory that is large enough to hold the largest variable in the union.
In this case it happens to be float variable with 4 bytes. The memory map of the union is as
shown below. 1058 1059 1060 1061 Memory Address

c
Members m
p

To access the union member, we can use the same syntax that we use for structure members.
i.e., purchased.m
purchased.c
while accessing, we should make sure that we are accessing the member whose value is
currently stored.
For example: purchased.m = 500;

22
UNIT4

purchased.p = 12.56;
printf(“ %d”, purchased.m);
would produce erroneous output.
Example: Program to illustrate the unions
union item
{ int m;
float x;
};
OUTPUT:

void main() m = 100


{ union item a; x = 315.27
a.m = 100; Now m =
printf (“m = %d\n”, a.m); 215
a.x = 315.27;
printf ( “x = %.2f\n”, a.x);
a.m = 215;
printf(“Now m = %d\n”, a.m);
}
DIFFERENCE BETWEEN STRUCTURES AND UNIONS

STRUCTURE UNION
Structure is a collection of related A union is a mutually exclusive collection
items of different data types. of elements of which only one should be
used at any given instance of time.
General form of structure definitions General form of union definitions
structTag_name union Tag_name
{ {
data-type Member1; data-type Member1;
data-type Member2; data-type Member2;
...... ......
}; };
Variable declaration is of the form: Variable declaration is of the form:
structTag_namevariabl-list; union Tag_namevariabl-list;
Size of the structure variable is equal Size of the union variable is equal to the
to the total no.of bytes occupied by largest member size in the union.

23
UNIT4

all the members.


All the members can be assigned At a given instance, only one member can
values at a given instant. be assigned a value.
Occupies a large amount of memory Effieciency usage of memory.
depending on the structure size.

24

You might also like