Professional Documents
Culture Documents
Lecture6 - Grouping of Different Data Elements
Lecture6 - Grouping of Different Data Elements
Lecture6 - Grouping of Different Data Elements
Programming in C++
Lecture 6
Grouping of Different Data Elements
*******Faculty of Computer Science*******
1
What is a structure?
• A structure (called record) is a collection of simple variables.
struct StructName {
type1 var1;
type2 var2;
.......
}; // need to terminate by a semi-colon
1. Defining a structure
Example:
8
Initializing Structure Members
// Page 138//partinit.cpp
#include <iostream>
using namespace std; Here’s the output:
struct part //specify a structure
{ int modelnumber; //ID number of widget Model 6244, part 373, costs $217.55
int partnumber; //ID number of widget part Model 6244, part 373, costs $217.55
float cost; //cost of part
};
int main(){
part part1 = { 6244, 373, 217.55F }; //initialize variable
part part2; //define variable
struct Point {
int x;
int y;
};
int main() {
Point p1 = {3, 4}; // declare and init members
cout << "(" << p1.x << "," << p1.y << ")" << endl; // (3,4)
int main() {
Person peter = {"Peter Jone", 18, 180.5, 70.5};
cout << "Name: " << peter.name << endl;
cout << "Age: " << peter.age << endl;
cout << "Height: " << peter.height << endl;
cout << "weight: " << peter.weight << endl;
return 0;
Faculty of Computer Science 12
}
Structures within Structures (Nested
Structure)
struct Distance
{
int feet;
float inches;
};
struct Room
{
Distance length;
Distance width;
};
Depth of Nesting
In theory, structures can be nested to any depth.
Eg.
apartment1.laundry_room.washing_machine.width.feet 14
Structure within structure
/*
* Testing struct (TestStruct1.cpp)
*/
#include <iostream>
using namespace std;
struct Point {
int x, y;
};
struct Rectangle {
Point topLeft;
Point bottomRight;
};
p1.x = 0; // p1 at (0, 3)
p1.y = 3;
p2.x = 4; // p2 at (4, 0)
p2.y = 0;
cout << "p1 at (" << p1.x << "," << p1.y << ")" << endl;
cout << "p2 at (" << p2.x << "," << p2.y << ")" << endl;
Rectangle rect;
rect.topLeft = p1;
rect.bottomRight = p2;
return 0;
}
Faculty of Computer Science 26
C++ structs
• C++ evolves the C's structs into OOP classes.
• C++ structs, like classes, may contain access specifiers (public, private,
protected), member functions, constructor, destructor and support
inheritance.
• The only difference for C++'s structs and classes is the struct's members
default to public access while class members default to private access, if
no access specifier is used.
enum Color {
RED = 1, GREEN = 5, BLUE =6
};
Output:
1,5,6
char ch = ‘a’; //character read from keyboard if( isWord == NO ) //if start of word,
isWord = YES; //then set flag
int wordcount = 0; //number of words read } while( ch != ‘\r’ ); //quit on Enter key