Structures and UNION C Programing
Structures and UNION C Programing
& UNIONS
WHAT IS A Structure ?
Structure is user defined data type which
is used to store heterogeneous data under
unique name. Keyword 'struct' is used to
declare structure.
1. Structure is always terminated with
semicolon (;).
2. Structure name as emp_info can be
later used to declare structure variables of
its type in a program.
General format -
struct emp_info
{
char emp_id[10];
char nm[100];
float sal;
}emp;
• Aceessing Structure Members :
structure_var.member;
struct emp_info
{
char emp_id[10];
char nm[100];
float sal;
}; struct emp_info emp;
Array in Structures :
#include <stdio.h>
#include <conio.h>
struct result
{
int rno, mrks[5];
char nm;
}res;
void main()
{
int i,total;
clrscr();
total = 0;
printf("\n\t Enter Roll Number : ");
scanf("%d",&res.rno);
printf("\n\t Enter Marks of 3 Subjects : ");
for(i=0;i<3;i++)
{
scanf("%d",&res.mrks[i]);
total = total + res.mrks[i];
}
printf("\n\n\t Roll Number : %d",res.rno);
printf("\n\n\t Marks are :");
for(i=0;i<3;i++)
{
printf(" %d",res.mrks[i]);
}
printf("\n\n\t Total is : %d",total);
getch();
}
OUTPUT-
Roll Number : 1
Marks are : 63 66 68
Total is : 197_
WHAT IS A UNION ?
A union, is a collection of variables of
different types, just like a structure.
However, with unions, you can only
store information in one field at any
one time.
General format of union : -
union union_name
{
<data-type> element 1;
<data-type> element 2;
<data-type> element 3;
}union_variable;
ACCESSING UNION FIELDS -
To access the fields of a union, use the dot
“operator(.)” just as you would for a structure.
union abc
{
int id;
char name;
float sal;
} a;
a. id
a.name
a.sal
The main difference between structure and union
is --
The size of the structure is sum of the size of each
member in the struchture.but size of the union is size
of Largest member in the union.
Usage
#include <stdio.h>
#include <conio.h>
union techno
{
int id;
char nm[50];
}tch;
void main()
{
clrscr();
printf("\n\t Enter developer id : ");
scanf("%d", &tch.id);
printf("\n\n\t Enter developer name : ");
scanf("%s", tch.nm);
printf("\n\n Developer ID : %d", tch.id);//Garbage
printf("\n\n Developed By : %s", tch.nm);
getch();
}
OUTPUT-