0% found this document useful (0 votes)
10 views

11 Structures

The document discusses structures in C++. It defines a Time structure with hour, minute, and second integer members. It demonstrates how to initialize a Time structure variable, access members using dot operators, and pass Time structures by reference. It also shows functions to print the time in universal and standard time formats by accessing the structure members. The document provides examples of declaring and defining a structure, initializing structure members, and displaying member values.

Uploaded by

amramr.elbrns78
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

11 Structures

The document discusses structures in C++. It defines a Time structure with hour, minute, and second integer members. It demonstrates how to initialize a Time structure variable, access members using dot operators, and pass Time structures by reference. It also shows functions to print the time in universal and standard time formats by accessing the structure members. The document provides examples of declaring and defining a structure, initializing structure members, and displaying member values.

Uploaded by

amramr.elbrns78
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

1

Outline

CSE131: Computer Programming

Structures
2

Structures
Outline
1 Introduction
2 Structure Definitions
3 Accessing Structure Members
4 Implementing a User-Defined Type Time with a struct
5 Implementing a Time Abstract Data Type with a class
3

1 Introduction

• Object-oriented programming (OOP)


– Encapsulates data (attributes) and functions (behavior) into
packages called classes
• Information hiding
– Class objects communicate across well-defined interfaces
– Implementation details hidden within classes themselves
• User-defined (programmer-defined) types: classes
– Data (data members)
– Functions (member functions or methods)
– Similar to blueprints – reusable
– Class instance: object
4

2 Structure Definitions

• Structures
– Aggregate data types built using elements of other types

struct Time { Structure tag


int hour;
int minute; Structure members
int second;
};
• Structure member naming
– In same struct: must have unique names
– In different structs: can share name
• struct definition must end with semicolon
5

2 Structure Definitions

• Self-referential structure
– Structure member cannot be instance of enclosing struct
– Structure member can be pointer to instance of enclosing
struct (self-referential structure)
• Used for linked lists, queues, stacks and trees
• struct definition
– Creates new data type used to declare variables
– Structure variables declared like variables of other types
– Examples:
• Time timeObject;
• Time timeArray[ 10 ];
• Time *timePtr;
• Time &timeRef = timeObject;
6

3 Accessing Structure Members

• Member access operators


– Dot operator (.) for structure and class members
– Arrow operator (->) for structure and class members via
pointer to object
– Print member hour of timeObject:
cout << timeObject.hour;

OR
timePtr = &timeObject;
cout << timePtr->hour;
– timePtr->hour same as ( *timePtr ).hour
• Parentheses required
– * lower precedence than .
7
4 Implementing a User-Defined Type Time with a
struct
• Default: structures passed by value
– Pass structure by reference
• Avoid overhead of copying structure
• C-style structures
– No “interface”
• If implementation changes, all programs using that struct
must change accordingly
– Cannot print as unit
• Must print/format member by member
– Cannot compare in entirety
• Must compare member by member
8
1 // Fig. 1: fig06_01.cpp
2 // Create a structure, set its members, and print it.
Outline
3 #include <iostream>
4
5 using std::cout;
fig06_01.cpp
6 using std::endl; (1 of 3)
7
8 #include <iomanip>
9
10 using std::setfill;
11 using std::setw;
Define structure type Time
12 with three integer members.
13 // structure definition
14 struct Time {
15 int hour; // 0-23 (24-hour clock format)
16 int minute; // 0-59
17 int second; // 0-59
18 Pass references to constant
19 }; // end struct Time Time objects to eliminate
20
copying overhead.
21 void printUniversal( const Time & ); // prototype
22 void printStandard( const Time & ); // prototype
23
9
24 int main()
25 { Use dot operator to initialize Outline
26 Time dinnerTime; // structure
variable members.
of new type Time
27
28 dinnerTime.hour = 18; // set hour member of dinnerTime
fig06_01.cpp
29 dinnerTime.minute = 30; // set minute member of dinnerTime (2 of 3)
30 dinnerTime.second = 0; // set second member of dinnerTime
31
32 cout << "Dinner will be held at ";
33 printUniversal( dinnerTime );
34 cout << " universal time,\nwhich is ";
35 printStandard( dinnerTime );
36 cout << " standard time.\n"; Direct access to data allows
37 assignment of bad values.
38 dinnerTime.hour = 29; // set hour to invalid value
39 dinnerTime.minute = 73; // set minute to invalid value
40
41 cout << "\nTime with invalid values: ";
42 printUniversal( dinnerTime );
43 cout << endl;
44
45 return 0;
46
47 } // end main
48
10
49 // print time in universal-time format
50 void printUniversal( const Time &t )
Outline
51 {
52 cout << setfill( '0' ) << setw( 2 ) << t.hour << ":"
53 << setw( 2 ) << t.minute << ":"
fig06_01.cpp
54 << setw( 2 ) << t.second; (3 of 3)
55
56 } // end function printUniversal Use parameterizedfig06_01.cpp
stream
57 manipulator setfill.
output (1 of 1)
58 // print time in standard-time format
59 void printStandard( const Time &t )
Use dot operator to access
60 { data members.
61 cout << ( ( t.hour == 0 || t.hour == 12 ) ?
62 12 : t.hour % 12 ) << ":" << setfill( '0' )
63 << setw( 2 ) << t.minute << ":"
64 << setw( 2 ) << t.second
65 << ( t.hour < 12 ? " AM" : " PM" );
66
67 } // end function printStandard

Dinner will be held at 18:30:00 universal time,


which is 6:30:00 PM standard time.

Time with invalid values: 29:73:00


11

EX1: Demonstrate Structures

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

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;
}
12
#include <iostream>
EX2: Combining Declaration and Definition using namespace std;

struct //no tag needed


{
int modelnumber; //ID number of widget
int partnumber; //ID number of widget
part
float cost; //cost of part
} part1; //definition goes here

int main()
{
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;
}
13
#include <iostream>

EX3: Combining Declaration and Definition


using namespace std;

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()
{
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;

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;
}
14
//Example4:

#include <iostream>
EX4: demonstrates structures using
using namespace std;

struct Distance //English distance


{
int feet;
float inches;
English measurements

};

int main()
{
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; //and
d3.feet++; //increase feet by 1
}
d3.feet += d1.feet + d2.feet; //add the feet

//display all lengths


cout << d1.feet << "\' " << d1.inches << "\" + ";
cout << d2.feet << "\' " << d2.inches << "\" = ";
cout << d3.feet << "\' " << d3.inches << "\"\n";

return 0;
}
15
#include <iostream>
using namespace std;
EX5: Initializing nested structures
////////////////////////////////////////////////////////////////
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 = {{13,6.5},{10,0.0}}; //define a
room

//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;
16
#include <iostream>
using namespace std;
EX6: Initializing nested structures
////////////////////////////////////////////////////////////////
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 = {{13,6.5},{10,0.0}}; //define a
room

//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;
17

Arrays in structs

• Two items are associated with a list:


– Values (elements)
– Length of the list
• Define a struct containing both items:
18

Arrays in structs (cont’d.)


19

Arrays in structs (cont’d.)


20

structs in Arrays

• Example:
21

structs in Arrays (cont’d.)


Enumeration

 Set of named integer constants that specifies all the


legal values that a variable of its type can have.
-Example:
enum Color {red, white, blue}
//or alternatively:
//typedef enum {red, white, blue} Color;
//in main function: define and initialize an enum variable:
Color c;
c = red;
c = white;
Enumeration

 The key point to understand about an


enumeration that each of the symbols stands
for an integer value and can be used in any
integer expression.
Enumeration

#include <stdio.h>
int main()
{
enum Days{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};

Days theDay;
int j = 0;
printf("Please day of the week (0 to 6)\n"); cin >> j;
theDay = Days(j);

if(theDay == Sunday || theDay == Saturday)


printf("Hurray it is the weekend\n");
else
printf("still at work ");
return 0;
}
25
#include <iostream>
using namespace std;
EX7: demonstrates enum types
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;
}
26
#include <iostream>
#include <conio.h>
using namespace std;

enum Answer { NO, YES }; //NO=0, YES=1


EX8: demonstrates enum types
int main()
{
Answer IsWord = NO; //YES when in a word, NO when in whitespace
char ch = 'a'; //character read from keyboard
int wordcount = 0; //number of words read

cout << "Enter a phrase:\n";


do
{
ch = getche(); //get character
if(ch==' ' || ch=='\r') //if white space,
{
if( IsWord == YES ) //and doing a word,
{
//then it's end of word
wordcount++; //count the
word
IsWord = NO; //reset flag
}
}
//otherwise, it's
else
//normal character
if( IsWord == NO ) //if start of word,
IsWord = YES; //then set
flag
}
while( ch != '\r' ); //quit on Enter key

cout << "\n---Word count is " << wordcount << "---\n";

return 0;
}

You might also like