OOP Lab 7
OOP Lab 7
Structures
Objectives
For example: You want to store some information about a person: his/her name,
citizenship number and salary. You can easily create different variables name, citNo,
salary to store this information separately.
However, in the future, you would want to store information about multiple persons.
Now, you'd need to create different variables for each information per person: name1,
citNo1, salary1, name2, citNo2, salary2
You can easily visualize how big and messy the code would look. Also, since no
relation between the variables (information) would exist, it's going to be a daunting
task.
A better approach will be to have a collection of all related information under a single
name Person, and use it for every person. Now, the code looks much cleaner,
readable and efficient as well.
This collection of all related information under a single name Person is a structure.
struct Person
char name[50];
int age;
float salary;
};
Once you declare a structure person as above. You can define a structure variable
as:
Person bill;
When structure variable is defined, only then the required memory is allocated by the
compiler.
Considering you have either 32-bit or 64-bit system, the memory of float is 4 bytes,
memory of int is 4 bytes and memory of char is 1 byte.
Suppose, you want to access age of structure variable bill and assign it 50 to it. You
can perform this task by using following code below:
bill.age = 50;
Output
Displaying Information.
Name: Magdalena Dankova
Age: 27
Salary: 1024.4
Displaying Information.
Name: Bill Jobs
Age: 55
Salary: 34233.4
Lab Task
2. Write a C++ Program to Add Two Distances (in inch-feet) using Structures.
3. Write a C++ program to store student information (name, roll no, marks) and
store the 5 student data in structure array and then display the result.