FYBCA Sem 2 C Lang Unit 3 - Structure and Union
FYBCA Sem 2 C Lang Unit 3 - Structure and Union
Ex.
structmyStructure {
int myNum;
char myLetter;
}S1;
int main() {
structmyStructure S2;
return 0;
}
Example program:
//To show the memory allocation
#include<stdio.h>
struct student
{
int rollno;
int marks;
char name[10];
};
int main()
{
int size;
struct student s; //Declaring a structure variable
size = sizeof(s);
What Is a Union?
A Union is a type of data that is user-defined. It is just like the
structure. The Union combines various objects of different sorts and sizes
together. A user can define a Union using many members, but only one of
them holds a value at any given time.
It provides you with an efficient way of using a single memory location
for various purposes. Thus, varying objects can share a similar location.
Defining a Union – A user must deploy the union statement for defining a
Union. It determines a new data type that has more than one member for
the intended program. Here’s the format of a union statement:
Syntax of Declaring a Union
union [union name]
{
type member_1;
type member_2;
...
typemember_n;
};
union employee
{
string name;
int phone;
string email;
}e1;
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
void main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
Output:
employee id : 101
employee name : SonooJaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
void main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
getch();
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz