Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

UNIT – IV

FUNCTIONS, STRUCTURES and UNIONS

Functions:
Introduction – using functions – Function declaration/ prototype – Function
definition – function call – return statement – Passing parameters – Scope of variables –
Storage Classes – Recursive functions.
Structure and Unions:
Introduction – Nested Structures – Arrays of Structures – Structures and Functions
– Unions – Arrays of Unions Variables.

Function:
A function is a self-contained block of statements that can be called for any number
of times. A function is a collection of logically related instructions which performs a specific
task.
Some of the predefined functions are: printf( ), scanf( ), strlen( ), strcpy( ) etc.
Here the set of instructions are specified for the above functions by C. We are directly
using these functions without having the knowledge of internal code for the above
functions. We can even call those functions any number of times. We can also define our
own user-defined functions.
By using functions there are some advantages. They are:
1. Functions are used for reusability of code
2. We can save time
3. Length of the program can be reduced by using functions
4. Program development becomes easy
5. Code-reusability increases
6. Code sharing becomes possible
Syntax: returntype function_name(list of arguments)
{
Executable statements;
Return statements;
}
Types of Functions
Functions are of 2 types:-
Library functions: The functions which are developed by c-developer
Ex: printf( ), scanf( ), clrscr( )
User-defined functions: The functions which are defined by the user.
Ex: any userdefined name, main( )
main( ) is a user-defined function but it act as a predefined/library function.

/* Creating a user-defined function */


void fun( ) //called function
{
printf(“Hello”); //calling the predefined printf function
printf(“welcome to functions”); //function definition
}
void main( )
{
1|Page
fun( ); //calling the user defined function
}

Function definition: It contains the return type, name, parameters list and body.
Function calling: Transferring control from one function to another function.
Calling function: A function which calls another function is called as calling function. In
the above example, fun( ), main( ), printf( ) are all calling functions
Called function: A function which gets called are called as called functions. Ex: fun( ) is
a called function which was called by main( ).
Declaration of a function:
Every function has its declaration and function definition. Function declaration
contains returntype, no of arguments, and function name.
Syntax: return type function_name(args list)
Ex: int square(int no);
void temp(float f)
In the above functions if you declare return type as void then we need not return
any value from that function, if we mention return type other than void we have to return
the value from that function. In the above example we have used int as return type, then
we have to return an integer number from the square function.

/* Returning a value from a function */


#include<stdio.h>
void main( )
{
int a=5,b=6,c; actual arguments
c=sum(a,b); // calling function sum by passing a and b
as arguments
}
int sum(int a,int b) //called function
{ formal arguments
int c;
c=a+b; // function definition
return c;
} here the return type is int we are returning the
int value

• A function can return only one value at a time.


• Arguments can also be called as parameters.
• Parameters are used to communicate data between the calling & called functions.
Actual arguments: the variables or the arguments used in the calling function are called
as actual arguments.
Formal arguments: the variables or the arguments used in the called function are called
as formal arguments.
The names of actual & formal arguments are may or may not the same. Even though
the names are same the “C” compiler treats them as different variables.

2|Page
Function Prototype
Prototypes are which tells the behaviour of the function. The prototype of a function
specifies its return type, name and the type of arguments.

Types 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:
• with no arguments and with no return value
• with no arguments and with return value
• with arguments and with no return value
• with arguments and with return value.
With no arguments and with no return value
These type of functions do not receive any values from the calling function no they
send any data to the calling function. So there is no communication between the calling
and called function are only program control will be transferred.
/* function with no args and no return values */
#include<stdio.h>
void main()
{
void message(); /* function declaration */
clrscr();
printf("control back to main");
message(); //function with no arguments
printf("control back to main\n");
}
void message()
{
printf("\ncontrol is in message function\n");
//function with no return values
}
Output:
control back to main
control is in message function
control back to main

With no arguments and with return value


These type of functions does not receive any values from calling function but returns
some value to the calling function.
/* function with no args and with return values */
#include<stdio.h>
void main()
{
int sum;
clrscr();
sum=cal_sum(); //function with no arguments
//return value from cal_sum( ) i.e., s will be
stored in sum
printf("sum of first ten natural nos is %d",sum);
3|Page
}
int cal_sum()
{
int i,s=0;
for(i=1;i<10;i++)
s=s+i;
return s; //function with return value
}
Output:
sum of first ten natural nos is 45

With arguments and with no return value


These type of functions send values from calling function to the called function but
called function will not return any value to the calling function. This is called as 1-way
communication
/* function with args and with no return values */
#include<stdio.h>
void main()
{
int a1=5,a2=5,a3=5;
void sum(int,int,int);
clrscr();
sum(a1,a2,a3); /* calling function with args and these args are
actual arguments will be copied into formal arguments */
}
void sum(int f1,int f2,int f3) /* formal arguments */
{
int s; /*function with no return values */
s=f1+f2+f3;
printf("Sum of 3 nos is..%d",s);
}
Output
Sum of 3 nos is..15

With arguments and with return value.


These type of functions send values from calling function to the called function and
called function will return the value to the calling function. This is called as 2-way
communication
/* function with args and with return values */
#include<stdio.h>
void main()
{
int a1=5,a2=5,a3=5,result;
int sum(int,int,int);
clrscr();
result=sum(a1,a2,a3); /* calling function with args */
printf("sum is ...%d",result);
}

4|Page
int sum(int f1,int f2,int f3)
{
/*function with return values */
return(f1+f2+f3);
}
Output
sum is ...15

Parameters Passing Mechanisms


The parameters can generally passed to a function in following 2 ways
1. call by value
2. call by reference
Call by value:
The value of each arguments are copied into the corresponding formal arguments.
Any changes done to the formal parameters have no effect on actual parameters, because
the actual parameters and formal parameters have separate memory locations. Calling a
function by passing the value is called as “call by value”.
//call by value mechanism
#include<stdio.h>
void main()
{
int a=10,b=50;
void swap(int,int);
clrscr();
printf("Before Swapping: %d %d\n",a,b);
swap(a,b);
printf("After Swapping: %d %d\n",a,b);
}
void swap(int a,int b)
{
int t;
t=a;
a=b;
b=t;
}
Output
Before Swapping: 10 50
After Swapping: 10 50

Call by Reference
The address of actual parameters is passed with calling function. The formal
parameters are pointer variables and they point to the same memory locations where the
actual parameters are pointing to. Hence any changes that are done to the formal
parameters effects the values of actual parameters. Calling a function by passing the
address of an actual argument is called as call by reference/address.
//call by reference mechanism
#include<stdio.h>
void main()

5|Page
{
int a=10,b=50;
void swap(int *,int *);
clrscr();
printf("Before Swapping: %d %d\n",a,b);
swap(&a,&b);
printf("After Swapping: %d %d\n",a,b);
}
void swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}
Output
Before Swapping: 10 50
After Swapping: 50 10

Recursion:
Function calling itself is called as recursion.
/* Factorial of a Number Using Recursion */
#include<stdio.h>
#include<conio.h>
int fact(int n) 5*fact(4); 5*24=120
{ 4*fact(3); 4*6=24
int f; 3*fact(2); 3*2=6
if(n==0) 2*fact(1); 2*1=2
return 1; 1*fact(0); return 1
else
f= n * fact(n-1); //recursion
return f;
}
void main()
{
int n,f;
clrscr();
printf("\n Enter the value of n:");
scanf("%d",&n);
f = fact(n);
printf("\n The factorial of %d is %d",n,f);
}
Output:
Enter the value of n: 6
The factorial of 6 is 720

6|Page
Storage Classes:
Every variable In C language has a powerful characteristic called Storage Class. There
are 3 basic places in a c-program where variables will be declared:
1. Inside the function
2. in the definition of function
3. Outside of all functions.
These variables are called as local variables, formal variables and global variables.
Local Variables:
A variable declared inside a function is called as local variables. A local variable will
be visible to the function in which it is declared.
Global Variables:
A variable declared in the global variable section are called as global variables. A
global variable can be used anywhere in the program. The proper place of declaration of
global variable is at the beginning of the main program.
#include<stdio.h>
#include<conio.h>
int a=10; // global variable can be accessed from
anywhere in the program

void main( )
{
clrscr();
{
int x=20; //local variable can be accessed
with in the function or within the block.
printf(“%d%d”,a,x);
}
printf(“\n%d”,a);
printf(“\n%d,%d”,a,x); //error ‘x’ not accessible
}
Output:
10 20
10

A variable defined in a block can be accessed within the block and all its inner
blocks. It is called as scope of variable.
While defining a variable we mentioned only its data type. To fully define a variable
we need to mention not only its data type, but also its storage class. If we don’t specify it
the compiler will assume a default storage class depending on the context where variable
is defined.
In ‘C there are 4 types of storage classes.
• auto
• static
• register
• extern

7|Page
The storage class tells us 4 things:
• Default initial value: what will be the default initial value of the variable as soon
as it is defined
• Location: where the variable would be stored
• Scope: where the variable can be accessed.
• Life: How long the memory remains reserved for the variable.

By default the storage class for any variable is auto

Auto Static Register Extern

Default
initial Garbage 0 Garbage 0
value

Location RAM RAM CPU Registers RAM

Local to the
Local to the block Local to the block
block where the Entire
Scope where the variable where the variable
variable is Program
is defined is defined
defined

As long as the As long as the


As long as the As long as the
control is within control is within
program is program is
Life the block where the block where
under under
the variable is the variable is
execution execution
defined defined

/* Auto Storage Class */


#include<stdio.h>
#include<conio.h>
void fun()
{
int a=10;
printf("%d\n",a);
a++;
}
void main()
{
fun();
fun();
fun();
}
8|Page
Output:
10
10
10
Here the storage class is auto be default. Auto variable life is as long as the control
is within the block where the variable is defined. Whenever the statement, int a=10; gets
executed, memory gets allocated to ‘a’ and the location is initialized with 10. Whenever the
control comes out of the fun( ) function block, the variable ‘a’ dies, i.e., memory allocated
gets released and hence the output.

/* Static Storage Class */


#include<stdio.h>
#include<conio.h>
void fun()
{
static int a=10;
printf("%d\n",a);
a++;
}
void main()
{
fun();
fun();
fun();
}
Output:
10
11
12
Static variable life is as long as the program is under the execution. These variables
gets memory allocated as soon as the program gets loaded into memory and memory gets
deallocated just before the termination of the program from the memory.
Static int a=10;
gets executed only once and when the control enters the fun () for the next time the line
gets ignored so it has the value what is has the last time. Its value persists between
different function calls, and hence the output. These are local to the block.

/* register storage class */


These variables are accessed much quickly than other variables as they reside in
the registers of the microprocessor. Because of the limited size and number of registers
available, few variables can actually be put in registers.
If the compiler does not allocate a machine register for a variable, then the variable
is treated as auto. We cannot use register for all types of variables (for ex., long, float,
double) because the CPU registers are usually 16-bit registers. As these are declared in
registers these cannot be referred by the pointer variable. The variables of most frequent
use should only be of register type.
#include<stdio.h>
#include<conio.h>

9|Page
void main()
{
register int i;
for (i=1;i<=100;i++)
printf("Hai");
}
Here the i gets accessed around 100 times so if it is made to reside in cpu registers
program execution will be fast.
Output:
HaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHai
HaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHai
HaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHai
HaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHaiHai

/* extern storage class */


When there is a need for a variable to be accessed in all the functions in a program
then the external variables serve the purpose.
#include<stdio.h>
#include<conio.h>
int a; /* by default a is 0 */
void main()
{
a=a+1;
clrscr();
printf("%d\t",a);
fun1();
fun2();
fun3();
fun4();
getch();
}
fun1()
{
a=a+10;
printf("%d\t",a);
}
fun2()
{
a=a+5;
printf("%d\t",a);
}
fun3()
{
a=a-2;
printf("%d\t",a);
}
fun4()
{

10 | P a g e
a=a+8;
printf("%d\t",a);
}

Output:
1 11 16 14 22

Structures:
An array is a collection of elements of similar type. Many a times we need to group
multiple types of data into a single entity. To do this, we use structures.
Ex: students details: sno, sname, age, course, fee
Employee details: eno, ename, age, basic
If it is an array we have to take number of arrays like sno to hold all sno’s, and
sname to hold all sname, age to hold all of the ages which is time consuming it increases
the code, etc. in such situations we declare a structure which is capable of holding all
these items in a single entity.
Definition:
STRUCTURE is a collection of variables under a single name. A structure is a
collection of heterogeneous elements.
Declaration of a structure
General format: struct tag_name
{
datatype member1;
datatype member2;
----
----
};
Ex: struct student
{
int sno,age,fee;
char sname[20],course[20];
};
This time no memory will be allocated to structure. This is only the definition of
structure that tells that there exists a user-defined data type student. Using this structure
we have to create the structure variables:
Struct student s1,s2,s3;
Or
struct student
{
int sno,age,fee;
char sname[20],course[20];
}s1,s2,s3;
At this point, we have created 3 instances or structure variables of user-defined
datatype student. Now memory will be allocated. The amount of memory allocated will be
the sum of all data members which form part of the structure.
S1 occupies(2+2+2+20+20)=46 bytes
S2 occupies(2+2+2+20+20)=46 bytes
S3 occupies(2+2+2+20+20)=46 bytes Totally it occupies 138 bytes
11 | P a g e
Initialization of structure
The structure initialization is followed by an (=) sign & a list of initialization values
separated by commas & enclosed in braces
struct student
{
int sno,age,fee;
char sname[20],course[20];
}s1={1,23,15000,”XYZ”,”BSc”};
They are placed in the structure members in the order in which the members are listed in
structure definition.
Accessing members of a structure
Structure members are accessed using the structure member operator(.) also called
dot operator, between the structure name and member name.
Syntax: structure_variable.member name;
Ex: struct student
{
int sno,age,fee;
char sname[20],course[20];
}s1;
s1.sno=23; //accessing structure member
s1.sname=”gvp”;
//storing & retrieving values from structure
#include<stdio.h>
#include<conio.h>
struct student
{
int rno,marks;
char name[20];
};
void main()
{
struct student s1;
clrscr();
printf("Enter the roll no:");
scanf("%d",&s1.rno);
printf("\nEnter the name:");
scanf("%s",&s1.name);
printf("\nEnter the marks:");
scanf("%d",&s1.marks);
printf("\nRoll No is %d",s1.rno);
printf("\nName is %s",s1.name);
printf("\nMarks are %d",s1.marks);
getch();
}
Output
Enter the roll no:234
Enter the name:gvp
Enter the marks:65

12 | P a g e
Roll No is 234
Name is gvp
Marks are 65

Structures with arrays


It is possible to declare an array of structures. The array will have individual
structures as its elements.
Syntax:
struct person struct person
{ {
char name[25]; OR char name[25];
float salary; float salary;
}per[10]; };
struct person per[10];
Here per is an array of 10 person structures.
Accessing elements in array of structures
In the above example, if you want to access the 5th structure, we can use the statement:
per[4];

per[4].name; //access the name of 5th structure


per[0].name[5]; //access 6th character of 1 structure name member
per[2].salary //access the salary of 3rd structure
Initializing array of structures
We can initialize an array of structures in the same way as a single structure.
Ex:
struct person
{
char name[25];
float salary;
};
struct person per[3]=
{
“mahesh”,3000,
“arjun”,5000,
“rana”,3445
};
Thus, per[0] will be assigned to the first set, per[1] to the second and so on.
Example
#include<stdio.h>
#include<conio.h>
struct empl
{
int eno;
char name[20];
};
void main()
{
struct empl e1[10];

13 | P a g e
int n,i;
clrscr();
printf("Enter the no of employees:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the %d empno and name:",i+1);
scanf("%d%s",&e1[i].eno,e1[i].name);
}
for(i=0;i<n;i++)
printf("Empno and name is:%d\t%s\n",e1[i].eno,e1[i].name);
getch();
}
Output:
Enter the no of employees:3
Enter the 1 empno and name:1 gvp
Enter the 2 empno and name:2 gvp1
Enter the 3 empno and name:3 gvp2
Empno and name is:1 gvp
Empno and name is:2 gvp1
Empno and name is:3 gvp2

Structures with functions


C supports the passing of structure values as arguments to functions in three methods:
1. Pass each member of the structure as an actual argument. But this becomes
unmanageable and inefficient when the structure size is large.
2. Pass the copy of an entire structure to the called function. Any changes to the
structure members in the called function will not affect the actual structure. It is
therefore necessary for the function to return the entire structure back to the calling
function.
3. Pass the address of a structure to the called function. This is similar to the way
arrays are passed to functions.
General form of sending a copy of a structure to the called function is:
Syntax: function_name(structure variable_name)
Called function takes the following form:
Data_type function_name(st_name)
struct_type st_name;
{
-----
-----
return(expression);
}

Structures within Structures


Structure within a structure is called as nested structures.
Example
#include<stdio.h>
#include<conio.h>

14 | P a g e
struct address
{
int dno;
char city[20];
};
struct student
{
int rno;
char name[20];
float fee;
struct address a; //structure within structure
};
void main()
{
struct student s1;
clrscr();
printf("Enter the roll no:");
scanf("%d",&s1.rno);
printf("\nEnter the name:");
scanf("%s",s1.name);
printf("\nEnter the fees:");
scanf("%f",&s1.fee);
printf("\nEnter the Door No:");
scanf("%d",&s1.a.dno);
printf("\nEnter the city:");
scanf("%s",s1.a.city);
printf("\nRoll No is %d",s1.rno);
printf("\nName is %s",s1.name);
printf("\nFees is %.2f",s1.fee);
printf("\nDno is %d",s1.a.dno);
printf("\nCity is %s",s1.a.city);
getch();
}
Output:
Enter the roll no:123
Enter the name:sreya
Enter the fees:25000.00
Enter the Door No:4245
Enter the city:vsp
Roll No is 123
Name is sreya
Fees is 25000.00
Dno is 4245
City is vsp

15 | P a g e
typedef
typedef is a keyword which is used to define an alias name for a datatype.
Ex: typedef int length;
Length becomes an alias name to int and variables can be declared by using the new
type name that has been created.
Length l1,l2;
Now l1,l2 is a variables of type length which is nothing but an alias name for int.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
typedef int gvp;
gvp a=45,b=45;
printf("Sum=%d",a+b);
getch();
}
Output
Sum=90

Unions:
Unions are similar to structures except the fact that memory allocated for a union
variable is memory required for the largest field.
The only difference between the structure and union is memory allocation.
Syntax:
Union unionname
{
Datamember1;
Datamember2;
};
Example
#include<stdio.h>
#include<conio.h>
union emp
{
char name[25];
int idno;
float salary;
}e1;
void main()
{
printf("Size of union is %d",sizeof(e1));
}
Output
Size of union is 25

16 | P a g e
Example
#include<stdio.h>
#include<conio.h>
union emps
{
double a;
float b[2];
char c[8];
}e1;
void main()
{
int i;
clrscr();
e1.a=1355.674;

e1.b[0]=2.3;
e1.b[1]=4.5;

printf("Enter 8 characters string:");


for(i=0;i<8;i++)
scanf("%c",&e1.c[i]);
printf("%.3lf\n",e1.a);
printf("%.2f,%.2f\n",e1.b[0],e1.b[1]);
for(i=0;i<8;i++)
printf("%c\n",e1.c[i]);

getch();
}
Output:
Enter 8 characters string: asdgghjk
2.713061780997133810000000000000000000000e+209
1078827923249377390000000.00,283381667918681262000000000.00
a
s
d
g
g
h
j
k

17 | P a g e

You might also like