Module5 Chapter1
Module5 Chapter1
struct struct–name
{
data_type var–
name; data_type
var–name;
...............
};
For example:
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
1. Simple Addition
In this techniques, make a list of all data types and add the memory required by each.
Consider a simple structure of an employee
void main()
{
struct employee e;
printf(“%d”, sizeof(e));
}
Example: C program to read and display the student details using structures.
#include<stdio.h>
struct student
{
int rnum;
char name[20];
int marks;
}s[60];
void main()
{
int i,n;
printf("Enter the number of students");
}
Output:
Enter the number of students: 5
Enter the roll number,
Name, Marks and Grade of
Student 1 details
14
Dhavan
89
Student 2 details
15
Karan
55
Student 3 details
11
Deepa
45
Student 4 details
12
Lakshmi
35
Student 5 details
10
Soma
68
Student Details are:
Roll_number Name Marks
14 Dhavan 89
15 Karan 55
11 Deepa 45
12 Lakshmi 35
10 Soma 68
void main()
{
POINT p1 = {2, 3};
display(p1.x, p1.y);
}
#include <stdio.h>
typedef struct
{
int x;
int y;
}POINT;
void display(POINT);
void display(POINT p)
{
printf("The coordinates of the point are: %d %d", p.x, p.y);
}
Example: Write a program using pointer to structure to initialize the members in the
structure.
#include<stdio.h>
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
void main()
{
struct student stud1, *ptr_stud1;
ptr_stud1 = &stud1;
ptr_stud1->r_no = 01;
strcpy(ptr_stud1->name, "Rahul");
strcpy(ptr_stud1->course, "BCA");
5.3 Union
Like structure, 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 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 a field, the existing data is replaced with the new
data.
};
int marks;
};
void 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? (Yes or No)
: "); scanf(&choice);
if(choice=='y' || choice=='Y')
{
printf("\n Enter the name : ");
scanf(“%s”,&stud.name);
}
else
{ printf("\n Enter the roll number :
"); scanf("%d", &stud.roll_no);
}
printf("\n Enter the marks : ");
scanf("%d", &stud.marks);
if(choice=='y' || choice=='Y')
printf("\n Name : %s ", stud.name);
else
Prepared by: Bhagyashree K. Asst. Professor, Dept of CSE, BrCE 11
p ("\n Marks : %d", stud.marks);
r
i
n
t
f
(
"
\
n
R
o
l
l
N
u
m
b
e
r
%
d
"
,
s
t
u
d
.
r
o
l
l
_
n
o
)
;
p
r
i
n
t
f
Prepared by: Bhagyashree K. Asst. Professor, Dept of CSE, BrCE 12
}
inprotected.com