Professional Documents
Culture Documents
STRUCTURES
Instructor : Rafia Hassan
Date: 14-03-2017
OBJECTIVES
Defining structure
(A Simple Structure)
Structure Variables
A structure is a collection of related elements or data items. It is
defined to declare its variables. A variable of structure type represents
the member of its structure. To declare a structure variable, the
structure is first defined, e.g:
struct part
{
int modelnum;
int partnum;
float price;
};
part part1 //define a structure variable
In the above example, modelnum, partnum and price are the members
of structure part. The variable part1 is declared as structure variable.
Accessing Structure Members
Example: part1.modelnum
The value into a structure variable can be assigned when it is declared. It is called
initialization of the structure variable. To initialize a structure variable, data is
assigned to the members of the structure; the data items are written in the same order
in which these have been defined in the structure.
struct part
{
int modelnum;
int partnum;
float price;
};
part part1 = {624, 300. 100000};
The values to be assigned to the structure members are surrounded by braces and
separated by commas. The first value in the list is assigned to the first member, the
second to the second member and so on.
EXAMPLE # 2
Structure variable in assignment statement
s3=s2;
Assign the value to the members of the structure. Define two structure
variables part1 and part2. Initialize part1, print out the values of its members,
assign part1 to part2, and print out is members. The output of the program
should be like:
Write a program that uses a structure called point to model a point. Define three
points, and have the user input values to two of them. then set the third point
equal to the sum of the other two, and display the value of the new point. The
output of the program should be like:
#include<iostream>
using namespace std;
struct point
{
int xco,yco;
};
void main()
{
point p1, p2,p3;
cout<<"\n Enter the co ordinates for p1 = ";
cin>>p1.xco>>p1.yco;
cout<<"\n Enter the co ordinates for p2 = ";
cin>>p2.xco>>p2.yco;
p3.xco = p1.xco+p2.xco;
p3.yco= p1.yco+p2.yco;
do
{
cout<<"\n Enter your area code, exchange, and number: ";
cin >>input.area_code>>input.exchange>>input.number;
cout<<"\n My number is ("<<mine.area_code<<")
"<<mine.exchange<<"-"<<mine.number<<endl;
cout<<"\n Your number is ("<<input.area_code<<")
"<<input.exchange<<"-"<<input.number;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}
while(getch()=='c');