Ch04 Structures
Ch04 Structures
Programming
Engr. Rashid Farid Chishti
[email protected]
Chapter 04: Structures
International Islamic University H-10, Islamabad, Pakistan
http://www.iiu.edu.pk
Structures
We have seen variables of simple data types,
such as float, char, and int.
Variables of such types represent one item of
information: a height, an amount, a count, and
so on.
But just as groceries are organized into bags,
employees into departments, and words into
sentences, it’s often convenient to organize
simple variables into more complex entities.
The C++ construction called the structure is
one way to do this.
A structure is a collection of simple variab-
les (can be of different types).
The data items in a structure are called the
members of the structure.
A Simple Structure
Let’s start off with a structure that contains three variables:
two integers and a floating-point number.
This structure represents an item in a widget company’s parts
inventory.
The structure is a kind of blueprint specifying what informat-
ion is necessary for a single part.
The company makes several kinds of widgets, so the widget
model number is the first member of the structure.
The number of the part itself is the next member, and the
final member is the part’s cost.
The next program defines the structure part, defines a
structure variable of that type called part1, assigns values to
its members, and then displays these values.
Program to use a structure (1/2)
// uses parts inventory to demonstrate structures
#include <iostream>
using namespace std;
struct part{ // declare a structure
int modelnumber; // ID number of widget
int partnumber; // ID number of widget part
float cost; // cost of part
};
int main(){
part part1; // define a structure
variable
// give values to structure members
part1.modelnumber = 6244;
part1.partnumber = 373;
part1.cost = 217.55F;
Program to use a structure (2/2)
// display structure members
cout << "Model " << part1.modelnumber;
cout << ", part " << part1.partnumber;
cout << ", costs $" << part1.cost << endl;
system("PAUSE");
return 0;
}
Initializing Structure Members (1/2)
// uses parts inventory to demonstrate structures
#include <iostream>
using namespace std;
struct part{ // declare a structure
int modelnumber; // ID number of widget
int partnumber; // ID number of widget part
float cost; // cost of part
};
int main(){ // initialize variable
part part1 = { 6244, 373, 217.55F };
part part2; // define variable
// display first variable
cout << "Model " << part1.modelnumber;
cout << ", part " << part1.partnumber;
cout << ", costs $" << part1.cost << endl;
Initializing Structure Members (2/2)