Lecture6 - Grouping of Different Data Elements

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

CST-12102

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.

• The variables in a structure can be of different types: some can be int,


some can be float, and so on.

• The data items in a structure are called the members of the


structure.

• A struct (structure) is a user-defined data structure that can be used


to hold a set of variables of different types (called members).

Faculty of Computer Science 2


What is a structure?
• To defined a struct:

struct StructName {
type1 var1;
type2 var2;
.......
}; // need to terminate by a semi-colon

• struct is an intermediate step towards Object-oriented Programming


(OOP).

• In OOP, use class that is an user-defined structure containing both


data members and member functions.
3
Syntax
struct structure_name {
variable declarations;
};
semicolon

1. Defining a structure
Example:

2. Declaration a structure variable


3. Accessing structure members
4
Structure Member in Memory

Faculty of Computer Science 5


Structure

Defining a structure variable


part part1, part2, part3;

Accessing Structure Members using dot operator


part2.modelnumber =6244;

Initializing Structure Members


part part1 = {6244, 373, 217.F};

Faculty of Computer Science 6


A Simple Structure
// Page 132 – 133// part.cpp
#include <iostream> Output:
using namespace std;
struct part //declare a structure Model 6244, part 373, costs $217.55
{
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
part1.modelnumber = 6244; //give values to structure members
part1.partnumber = 373;
part1.cost = 217.55F; //display structure members
cout << “Model “ << part1.modelnumber;
cout << “, part “ << part1.partnumber;
cout << “, costs $” << part1.cost << endl;
return 0;
}
Faculty of Computer Science 7
Accessing Structure Member

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

cout << “Model “ << part1.modelnumber; //display first variable


cout << “, part “ << part1.partnumber;
cout << “, costs $” << part1.cost << endl;

part2 = part1; //assign first variable to second


//display second variable
cout << “Model “ << part2.modelnumber;
cout << “, part “ << part2.partnumber;
cout << “, costs $” << part2.cost << endl;
return 0;
} 9
Initializing Structure Members
// Page 139 // englarea.cpp// demonstrates structures using English measurements
#include <iostream> output:
struct Distance //English distance Enter feet: 10
{ int feet;
float inches;};
Enter inches: 6.75
int main() 10’-6.75” + 11’-6.25” = 22’-1”
{ Distance d1, d3; //define two lengths
Distance d2 = { 11, 6.25 }; //define & initialize one length
//get length d1 from user
cout << “\nEnter feet: “; cin >> d1.feet;
cout << “Enter inches: “; cin >> d1.inches;
//add lengths d1 and d2 to get d3
d3.inches = d1.inches + d2.inches; //add the inches
d3.feet = 0; //(for possible carry)
if(d3.inches >= 12.0) //if total exceeds 12.0,
{ //then decrease inches by 12.0
d3.inches -= 12.0;
d3.feet++; //increase feet by 1
} //display all lengths
d3.feet += d1.feet + d2.feet; //add the feet
cout << d1.feet << “\’-” << d1.inches << “\” + “;
cout << d2.feet << “\’-” << d2.inches << “\” = “;
cout << d3.feet << “\’-” << d3.inches << “\”\n”;
return 0; } Faculty of Computer Science 10
/* Testing struct (TestStruct.cpp) */
#include <iostream>
using namespace std;

struct Point {
int x;
int y;
};

int main() {
Point p1 = {3, 4}; // declare and init members
cout << "(" << p1.x << "," << p1.y << ")" << endl; // (3,4)

Point p2 = {}; // declare and init numbers to defaults


cout << "(" << p2.x << "," << p2.y << ")" << endl; // (0,0)
p2.x = 7;
p2.y = 8;
cout << "(" << p2.x << "," << p2.y << ")" << endl; // (7,8)
return 0; Faculty of Computer Science 11
}
Example: struct Person
// A struct can contains members of different types.
/* Testing struct (TestStructPerson.cpp) */
#include <iostream>
#include <string>
using namespace std; Name: Peter Jone
Age: 18
struct Person { Height: 180.5
string name; weight: 70.5
int age;
double height;
double weight;
};

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;
};

Faculty of Computer Science 13


Structure within structure
Accessing Nested Structure Members
• dot operator twice to access
the structure members.
Eg- dining.length.feet = 13;

Initializing Nested Structures


Eg.
Room dining = { {13, 6.5}, {10, 0.0}};

Depth of Nesting
In theory, structures can be nested to any depth.
Eg.
apartment1.laundry_room.washing_machine.width.feet 14
Structure within structure

FIGURE 4.6 Dot operator and nested structures


Faculty of Computer Science 15
Structure within structure
#include <iostream>
using namespace std;
struct Distance //English distance
{ int feet;
float inches;
};
struct Room //rectangular area
{
Distance length; //length of rectangle
Distance width; //width of rectangle
};
int main()
{
Room dining; //define a room
dining.length.feet = 13; //assign values to room
dining.length.inches = 6.5;
dining.width.feet = 10;
dining.width.inches = 0.0;
Faculty of Computer Science 16
Structure within structure

//convert length & width


float l= dining.length.feet + dining.length.inches/12;
float w = dining.width.feet + dining.width.inches/12;

//find area and display it


cout << “Dining room area is “ << l * w << “ square feet\n” ;
return 0;

Faculty of Computer Science 17


Example: structs Point and Rectangle

/*
* Testing struct (TestStruct1.cpp)
*/
#include <iostream>
using namespace std;

struct Point {
int x, y;
};

struct Rectangle {
Point topLeft;
Point bottomRight;
};

Faculty of Computer Science 18


int main() {

Point p1, p2;

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;

cout << "Rectangle top-left at (" << rect.topLeft.x


<< "," << rect.topLeft.y << ")" << endl;
cout << "Rectangle bottom-right at (" << rect.bottomRight.x
<< "," << rect.bottomRight.y << ")" << endl;

Faculty of Computer Science 19


return 0; }
A Card Game Example
// cards.cpp
// demonstrates structures using playing cards
#include <iostream> card card2 = { jack, hearts }; //initialize card2
using namespace std; cout << “Card 2 is the jack of hearts\n”;
const int clubs = 0; //suits card card3 = { ace, spades }; //initialize card3
cout << “Card 3 is the ace of spades\n”;
const int diamonds = 1; prize = card3; //copy this card, to remember it
const int hearts = 2;
const int spades = 3; cout << “I’m swapping card 1 and card 3\n”;
const int jack = 11; //face cards temp = card3; card3 = card1; card1 = temp;
const int queen = 12; cout << “I’m swapping card 2 and card 3\n”;
const int king = 13; temp = card3; card3 = card2; card2 = temp;
const int ace = 14; cout << “I’m swapping card 1 and card 2\n”;
temp = card2; card2 = card1; card1 = temp;
struct card
{ cout << “Now, where (1, 2, or 3) is the ace of spades? “;
int number; //2 to 10, jack, queen, king, ace cin >> position;
int suit; //clubs, diamonds, hearts, switch (position)
spades {case 1: chosen = card1; break;
}; case 2: chosen = card2; break;
int main() case 3: chosen = card3; break;}
if(chosen.number == prize.number && // compare cards
{ chosen.suit == prize.suit)
card temp, chosen, prize; //define cards cout << “That’s right! You win!\n”;
int position; else
card card1 = { 7, clubs }; //initialize card1 cout << “Sorry. You lose.\n”;
cout << “Card 1 is the 7 of clubs\n”; return 0;
} 20
Array of Structure

Faculty of Computer Science 21


Array of structure
// Page 277// partaray.cpp
#include <iostream>
const int SIZE = 4; //number of parts in array
struct part //specify a structure
{ int modelnumber; //ID number of widget
int partnumber; //ID number of widget part
float cost; //cost of part
};
int main()
{
int n;
part apart[SIZE]; //define array of structures

Faculty of Computer Science 22


Array of struture
for(n=0; n<SIZE; n++) //get values for all members
{
cout << endl; Here’s some sample input:
Enter model number: 44
cout << “Enter model number: “;
Enter part number: 4954
cin >> apart[n].modelnumber; //get model number Enter cost: 133.45
cout << “Enter part number: “; Enter model number: 44
cin >> apart[n].partnumber; //get part number Enter part number: 8431
cout << “Enter cost: “; Enter cost: 97.59
Enter model number: 77
cin >> apart[n].cost; //get cost
Enter part number: 9343
} Enter cost: 109.99
cout << endl; Enter model number: 77
for(n=0; n<SIZE; n++) //show values for all members Enter part number: 4297
Enter cost: 3456.55
{ cout << “Model “ << apart[n].modelnumber;
Model 44 Part 4954 Cost 133.45
cout << “ Part “ << apart[n].partnumber; Model 44 Part 8431 Cost 97.59
cout << “ Cost “ << apart[n].cost << endl; Model 77 Part 9343 Cost 109.99
} Model 77 Part 4297 Cost 3456.55
return 0;
} Faculty of Computer Science 23
Array within Structure

Faculty of Computer Science 24


Array within structure
// Page 277// partaray.cpp
#include <iostream>
using namespace std;
struct student
{ int roll;
char name[20];
int mark[3];
int total;
float avg;
};
int main()
{
int i;
student s;
cout<<“Enter student roll: “;
cin>>s.roll;
Faculty of Computer Science 25
cout<<“Enter student name: “;
cin>>s.name;
s.total = 0;
for(i=0;i<3;i++) {
cout<<“Enter marks “<<i+1<<“ : “;
cin>>s.mark[i];

s.total = s.total + s. mark[i];


}
s.avg = s.total/3;
cout<< “\nRoll : “ <<s.roll;
cout<< “\nName : “ <<s.name;
cout<< “\nTotal : “ <<s.total;
cout<< “\nAverage : “ <<s.avg;

return 0;
}
Faculty of Computer Science 26
C++ structs
• C++ evolves the C's structs into OOP classes.

• The legacy C's structs contain public data members.

• 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.

• Also, C++ structs default to public-inheritance whereas classes default


to private-inheritance.

Faculty of Computer Science 27


Enumerations (enum)
• An enum is a user-defined type of a set of named constants,
called enumerators.
• An enumeration define the complete set of values that can be
assigned to objects of that type.
• An enum declaration defines the set of all names that will be
permissible values of the type/list of all possible values.
• Use standard arithmetic operators on enum type.

Faculty of Computer Science 28


Other Examples
enum months { Jan, Feb, Mar, Apr, May, Jun,Jul, Aug, Sep, Oct,
Nov, Dec };
enum switch { off, on };
enum meridian { am, pm };
enum chess { pawn, knight, bishop, rook, queen, king };
enum coins { penny, nickel, dime, quarter, half-dollar, dollar };

Faculty of Computer Science 29


Enumerations

FIGURE 4.9 Usage of ints and enums.


Faculty of Computer Science 30
Enumerations (enum)
• The enumerators are represented internally as integers.
• Use the names in assignment, not the numbers.
• It will be promoted to int in arithmetic operations.
• By default, they are running numbers starting from zero.
• Can be assigned different numbers, e.g.,

enum Color {
RED = 1, GREEN = 5, BLUE =6
};

Output:
1,5,6

Faculty of Computer Science 31


Days of the Week
#include <iostream>
using namespace std;
//specify enum type
enum days_of_week { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
int main()
{
days_of_week day1, day2; //define variables
//of type days_of_week
day1 = Mon; //give values to
day2 = Thu; //variables
int diff = day2 - day1; //can do integer arithmetic
cout << “Days between = “ << diff << endl;
if(day1 < day2) //can do comparisons
cout << “day1 comes before day2\n”;
return 0;
} Faculty of Computer Science 32
Changing Default values of enum

Faculty of Computer Science 33


enum and switch values

Faculty of Computer Science 34


Enumerations Example
// Page 152 // wdcount.cpp
#include <iostream>
if( isWord == YES ) //and doing a word,
using namespace std;
#include <conio.h> //for getche() {
//then it’s end of word
enum itsaWord { NO, YES }; //NO=0, YES=1 wordcount++; //count the word
isWord = NO; //reset flag
int main() }
{ } //otherwise, it’s
itsaWord isWord = NO;
//YES when in a word, else //normal character
//NO when in whitespace

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

cout << “Enter a phrase:\n”; cout << “\n---Word count is “ <<


do { wordcount << “---\n”;
ch = getche(); //get character
if(ch==’ ‘ || ch==’\r’) //if white space, return 0; 35
{
}
// cardenum.cpp //pg153
#include <iostream>
using namespace std;
const int jack = 11; prize = card3; //copy this card, to remember it
//2 through 10 are unnamed integers cout << “I’m swapping card 1 and card 3\n”;
const int queen = 12; temp = card3; card3 = card1; card1 = temp;
const int king = 13; cout << “I’m swapping card 2 and card 3\n”;
const int ace = 14; temp = card3; card3 = card2; card2 = temp;
enum Suit { clubs, diamonds, hearts, spades }; cout << “I’m swapping card 1 and card 2\n”;
temp = card2; card2 = card1; card1 = temp;
struct card cout << “Now, where (1, 2, or 3) is the ace of spades? “;
{ cin >> position;
int number; //2 to 10, jack, queen, king, ace switch (position)
Suit suit; //clubs, diamonds, hearts, spades { case 1: chosen = card1; break;
}; case 2: chosen = card2; break;
int main() case 3: chosen = card3; break;
{ }
card temp, chosen, prize; //define cards if(chosen.number == prize.number &&
int position; chosen.suit == prize.suit)
card card1 = { 7, clubs }; //initialize card1 cout << “That’s right! You win!\n”;
cout << “Card 1 is the seven of clubs\n”; else
card card2 = { jack, hearts }; //initialize card2 cout << “Sorry. You lose.\n”;
cout << “Card 2 is the jack of hearts\n”; return 0;
card card3 = { ace, spades }; //initialize card3 }
cout << “Card 3 is the ace of spades\n”;
Faculty of Computer Science 36
Summary
• Structures are typically used to group several data items together to form a
single entity.
• A structure definition lists the variables that make up the structure.
• Structure variables are treated as indivisible units in some situations (such as
setting one structure variable equal to another), but in other situations their
members are accessed individually (often using the dot operator).
• An enumeration is a programmer-defined type that is limited to a fixed list
of values.
• A declaration gives the type a name and specifies the permissible values,
which are called enumerators.
• Internally the compiler treats enumeration variables as integers.
• Structures should not be confused with enumerations.
• Structures are a powerful and flexible way of grouping a diverse collection
of data into a single entity.
• An enumeration allows the definition of variables that can take on a fixed set
of values that are listed (enumerated) in the type’s declaration.
Faculty of Computer Science 38

You might also like