Module 5 Principles of programming using C
Module 5: Structure, Union and Enumerated data type
Structure:
Structure is basically a user-defined data type that can store related information together.
The major difference between structure and an array is that, an array contains related
information of the same data type.
Structure declaration:
A structure is declared using the keyword struct followed by a structure name .all the variable of
the structure is declared within the structure.
Syntax 1:
Struct structure name
Data type var-name;
Data type var-name;
……..
};
Example:
Struct student
int r_no;
char name[20];
char course[20];
float fees;
};
Now ,structure has become user defined data type .exach var-name declared within a structure is
called a member of the structure.
Module 5 Principles of programming using C
Syntax 2:
Struct student
int r_no;
char name[20];
char course[20];
float fees;
}stud1,stud2;
In declaration ,we declare two variable stud1 and stud2 of the structure student.So,if you want
Tto declare more than one variable of the structure,then separate the variable using comma.
R_no
name
course
fees
fig: memory allocation for a structure variable
Example1: Declare a structure to store information about the points in the coordinate
system
Solution:
Struct point
int x;
int y;
}
Module 5 Principles of programming using C
Example2: Declare a structure to store customer information .
Solution:
Struct customer
int cust_id;
char name[20];
char address[20];
long int phone_num;
int DOB;
Typedef Declaration:
The typedef (derived from type definition) keyword enables the programmer to create a new type
name for an existing data type. By using typedef, no new data is created; rather an alternate name
is given to a known data type.
Syntax:
Typedef existing data type new data type;
Example:
Typedef int INTEGER;
Then INTEGER is the new name of data type int. To declare variables using the new data type
name, precede the variable name, precede the variable name with the data type
name.Therefore,to define an integer variable, we may now write
INTEGER num=5;
Initialization of structure:
Initializing a structure means assigning some constants to the members of the structure. When
the user does not explicitly initialize the structure, then C automatically does that.For int and
float members, the values are initialized to zero and char and string members are initialized to
the ‘\0’ by default.
Syntax:
Module 5 Principles of programming using C
Struct struct_name
Data_type member_name1;
Data_type member_name2;
Data_type member_name3;
……………….
}struct_var={constant1,constant2,constant3,….};
OR
Struct struct_name
Data_type ember _name1;
Data_type ember _name2;
Data_type ember _nam3;
…….
};
Struct struct_name struct_var={constant1,constant2,constant3,…..};
Example:
Struct student
int rollno;
char name[20];
char course[20];
float fees;
}stud1={01,”Rahul”,”BCA”,45000};
Module 5 Principles of programming using C
OR
Struct student
int rollno;
char name[20];
char course[20];
float fees;
Struct student stud1={01,”Rahul”,”BCA”,45000};
Accessing the members of a structure:
A structure member variable is generally accessed using a ‘.’(dot) operator.
Syntax:
Struct_var.member_name;
The dot operator is used to select a particular member of the structure.To assign value to the
individual data members of the structure variable stud1.
Stud1.rollno=01;
Stud1.name=”Rahul”;
Stud1.course=”BCA”;
Stud1.fees=45000;
To input values for data members of the structure variable stud1 we can write,
Scanf(“%d”,&stud1.rollno);
Scanf(“%s”,&stud1.name);
Similarly,to print the values of structure variable stud1,we may write,
Printf(“%s”,stud1.course);
Module 5 Principles of programming using C
Printf(“%f”,stud1.fees);
Copying and comparing structure:
Assign a structure to another structure of the same type.
Example:
Two structure Variables stud1 and stud2 of type struct student is given as:
Struct student stud1={01,”Rahul”.”BCA”,45000};
Then to assign one structure variable to another we will write stud2=stud1;
Nested structures:
Structure can be placed within another structure, i.e., a structure may contain another structure as
its member. A structure that contains another structure as its member is called a nested structure.
Structures and functions:
A function may access the members of a structure in three ways as
Passing individual
members
Passing the entire structure
Passing structures to
functions Passing the address of the
structure
Passing individual members:
To pass any individual member of the structure to a function, we must use the direct
selection operator to refer to the individual members for the actual parameters.
The called program does not know if the two variables are ordinary variables or structure
members.
Example:
#include<stdio.h>
Typedef struct
{
int x;
Module 5 Principles of programming using C
int y;
}POINT;
void display(int,int);
main()
{
POINT p1={2,3};
display (p1.x,p1.y);
return 0;
}
void display(int a,int b)
{
printf(“the coordinates of the point are”%d%d”,a,b);
}
Output:
The coordinates of the point are : 2 3
Passing the entire structure:
Just like any other variable, we can pass an entire structure as a function argument. when a
structure is passed as an argument, it is passed using the call by value method, i.e., a copy of
each member of the structure is made.
The general syntax for passing structure to a function and returning a structure can be given as,
Struct struct_name func_name(struct struct_name struct_var);
Example:
#include<stdio.h>
typedef struct
int x;
int y;
}POINT;
Module 5 Principles of programming using C
void display(POINT);
main()
POINT p1={2,3};
display (p1);
return 0;
void display(POINT p)
printf(“the coordinates of the point are”%d%d”,a,b);
Output:
The coordinates of the point are :2 3
Passing structures through pointers:
Passing large structures to function using the call by value method is very inefficient.Thereferore
it is preferred to pass structures through pointers
Syntax:
Struct struct_name
Data type member_name1;
Data type member_name2;
Data type member_name3;
…………
}*ptr;
Module 5 Principles of programming using C
OR
Struct struct_name *ptr;
For our student structure we can declare a pointer variable by writing.
Struct student *ptr_stud, stud;
To assign the address of stud to the pointer using the address operator(&) as we would do in case
of any other pointer. So to assign the address, we will write.
ptr_stud=&stud;
to access the members of the structure one way is to write.
(*ptr_stud).roll_no;
Since parenthesis have a higher precedence than *, writing this statement would work well.
C introduces a new operator to do the same task. This operator is known as the pointing to
operator ().
ptr_stud roll_no=01;
Union:
Similar to structures, a union is a collection of variables of different data types. The only
difference between a structure and a union is that in case of unions, you can only store
information in one field at any one time.
To better understand a union, think of it as a chunk of memory that is used to store
variables of different types. When a new value is assigned to afield, the existing data is
replaced with the new data.
Unions are used to save memory. They are useful for applications that involve multiple
members, where values need not be assigned to all the members at any one time.
Declaring a Union:
the syntax for declaring a union is
union union name
{
Data type var-name;
Data type var-name;
…..
Module 5 Principles of programming using C
};
Accessing a member of a union:
A member of a union can be accessed using the same syntax as that of a structure.To access the
field of a union,use the dot operator(.).
Syntax:
Union variable name .member name;
Initializing unions:
#include<stdio.h>
typedef struct POINT1
int x;
int y;
typedef union POINT2
int x;
int y;
};
main()
POINT p1={2,3};
//point p2={4,5};illegal with union
POINT2=p2;
P2.x=4;
P2.y=5;
Module 5 Principles of programming using C
Printf(“\n the coordinates of p1 are %d and %d”,p1.y);
Printf(“\n thye coordinated of p2 are %d and %d”,p2.y)’
return o;
Output:
The coordinates of p1 are 2 and 3
The coordinates of p2 are 5 and 5
In this code POINT1 is a structure and POINt2 is a union. However both the declarations
are almost same in main (), you see a point of difference while initializing values. The
fields of a union cannot be initialized all at once.
Union inside structures:
#include<stdio.h>
Struct student
Union
Char name[20];
int roll_no;
};
main()
Struct student stud;
Char choice;
printf(“\n you can enter the name or roll number of the student”);
printf(“\n do you want to enter the name?(Y or N):”);
gets(choice);
Module 5 Principles of programming using C
if(choice==’y’ || choice==’Y’)
printf(“\n eneter the name:”);
gets(stud.name);
}
else
Printf(“\n enter the roll number:”);
Scanf(“%d”,&stud.rollno);
printf(“\n enter the marks;
Scanf(“%d”,&stud.marks);
if(choice==’Y’ || choice==’y’)
printf(“\n Name:%s”,stud.name);
else
printf(“\n Roll number:%d”,stud.rollno);
return 0;
Enumerated data types:
The enumerated data type is a user defined type based on the standard integer type.
An enumeration consist of a set of named integer constants.
In an enumerated type each integer value is assigned an identifier.
To define enumerated data type we use the keyword enum,which is the abbreviation for
enumerate.
Enumerations create new data types to contain values that are not limited to the values
that the fundamental data types may take.
Syntax:
enum enumeration name{identifier1,identifier2,…..identifier 3};
Module 5 Principles of programming using C
The enum keyword is basically used to declare and initialize a sequence of integer constants.
Example: which creates a new type of variable called COLOURS to store colour constants
enum COLOURS {RED, BLUE, BLACK, GREEN, YELLOW, PURPPLE, WHITE};
COLOUR is the name given to the set of constants. In case you do not assign any value to a
constant,the default value for the first one in the list –RED has the value of 0.the rest of the
undefined constants have a value 1 more than its previous one.
RED=0, BLUE=1,BLACK=2,gREEN=3,YELLOW=4,PURPLE=5,WHITE=6
If you want to explicitly assign values to these integer constants then you should
specifically mention those values as:
enum COLOUR{RED=2,BLUE,BLACK=5,GREEN=7,YELLOW,PURPLE,WHITE=15};
as a result of this statement
RED=2,BLUE=3,BLACK=5,GREEN=7,YELLOW=8,PURPLE=9,WHITE=15.
Example:
#include<stdio.h>
main()
enum{RED=2,BLUE,BLACK=5,GREEN=7,YELLOW,PURPLE,WHITE=15};
Printf(“\n RED=%d”,RED);
Printf(“\n BLUE=%d”,BLUE);
Printf(“\n BLACK=%d”,BLACK);
return0;
Output:
RED=2
BLUE=3
BLACK=5
Module 5 Principles of programming using C
enum variable:
syntax for declaring a variable of an enumerated data type can be given as
1 .enumeration name variable name;
Example:
enum COLOURS bg_colour;
2. enumeration name {identifier1,identifier2,identidier3…}variable name;
Example:
enum COLOURS{RED,BLUE,BLACK,GREEN,YELLOW,PURPLE,WHITE}bg_colour,fore_colour;
Using type def keyword:
typedef enum COLOUR colour;
Then declare variable by writing
Colour forecolour=RED;
Assigning values to enumerated variable:
Once the enumerated variable has been declared values can be stored in it.however an
enumerated variable can hold only declared values for the type.
Example:
To assign the colour black to the background colour as
bg_colour=BLACK;
Once an enumerated variable has been assigned a value,we can store its value in another
variable of the same type.
enum COLOUR bg_colour,border_colour;
bg_colour=BLACK;
border_colour=bg_colour;
Module 5 Principles of programming using C
Differentiate between Structures and Unions.
Structures Unions
struct keyword is used to define a structure. union keyword is used to define a union.
Every member within structure is assigned a In union, a memory location is shared by all the
unique memory location. data members.
It enables you to initialize several members at It enables you to initialize only the first member
once. of union.
The total size of the structure is the sum of the The total size of the union is the size of the largest
size of every data member. data member.
We can retrieve any member at a time. We can access one member at a time in the union.
It supports flexible array. It does not support a flexible array.
Write a c program that accepts a structure variable as parameters to a function from a
function call.
#include<stdio.h>
#include<string.h
>struct student
{
int rollno;
char name[50]; float percentage;
};
void func(struct student
s1);int main( )
{
struct student
s1;s1.id = 1;
strcpy(s1.name,
“Suvika”);
s1.percentage = 85.5;
func(s1);
return 0;
}
void func(struct student s1)
{
printf(“ID = %d”, s1.id);
printf(“Name = %s”, s1.name);
printf(“Percentage = %f”, s1.percentage);
Module 5 Principles of programming using C
Write a program to read details of 10 students and to print the marks of the student if
his name is givenas input.
#include<stdio.h>
#include<string.h
>struct student
{
int rollno;
float marks,
char name[100], grade[10];
};
void main()
{
struct student s[20];int i;
char checkname[100];
for(i=0;i<10;i++)
{
printf("Enter the detail of %d
students",i+1);printf("Enter rollno=");
scanf("%d",&s[i].rollno);
printf("Enter marks=");
scanf("%f",&s[i].marks);
printf("Enter Name=");
scanf("%s",s[i].name);
printf("Enter Grade=");
scanf("%s",s[i].grade);
}
printf(“Enter the student name to check the
marks”);scanf(“%s”, checkname);
for(i=0;i<10;i++)
{
Module 5 Principles of programming using C
if((strcmp(checkname, s[i].name)) == 0)
printf(“The marks of the student is %f”, s[i].marks);
}
}