Professional Documents
Culture Documents
Unit - Iv Functions, Structures and Unions
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.
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.
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
4|Page
int sum(int f1,int f2,int f3)
{
/*function with return values */
return(f1+f2+f3);
}
Output
sum is ...15
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.
Default
initial Garbage 0 Garbage 0
value
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
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
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
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
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;
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