Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition.

Similar presentations


Presentation on theme: "Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition."— Presentation transcript:

1 Lecture 26: Structures / struct s/

2 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition ( typedef statement) t Structs and functions t Structs as input parameters and return values t Arrays of structs t Pointers to structs t Demo programs t Exercises

3 3 Reminder on data structs t Data structure: composite of related data items stored in memory under the same name. t Typical data structures available in most PL: –Array: already discussed –Structure: to discuss today (same as record in Pascal) – Class: structure with functions /methods/ (OOP) – File (I/O processing aside keyboard and screen)

4 4 Reminder on arrays Array: a collection of data items of the same type. Reminder: Simple data type: Data type used to store a single value. scalar variable stores a single value. Therefore array may store many data items of the same type.

5 5 Basics of structures Definition: A collection of simple variables. A data type for a record composed of multiple components. These components may be the same data type or may be not the same data type.

6 6 Struct definition (declaration) struct specifier – applying struct reserved word. struct Date { int day, month, year; }; This is a template only which does not occupy storage /memory cells/.

7 7 Struct definition (declaration) OR

8 8 Struct definition (declaration) Applying typedef statement typedef struct { int day, month, year; } Date; This is a template only which does not occupy storage /memory cells/.

9 9 The struct template t The struct template has to be globally defined. t It is recommended The struct template to be typed outside any function body. t Globally defined struct template makes it visible in all functions that follow the definition.

10 10 Basics of structs t Arrays are data structures to store a collection of data items of the same type.  Structs as opposed to arrays, are data structures to store collections of related data items that have different types. t The individual component of a struct is called a member.

11 11 Struct definition (declaration) struct specifier – no storage occupying sample struct Person { char name[20]; char gender; int age; float grade; };

12 12 Struct definition (declaration) OR

13 13 Struct definition (declaration) Applying typedef reserved word typedef struct { char name[20]; char gender; int age; float grade; } Person;

14 14 Struct definition (declaration) Member of the Person struct char name[20] can be replaced to char *name or string name

15 15 Referencing a struct type How to define a struct as a variable to be a scalar, an array or a pointer? Date a, b; Date c[20]; Date *ptr1;

16 16 Referencing a struct type How to define a struct as a variable to be a scalar, an array or a pointer? Person John, Mary; Person ClassCos120a[20]; Person ClassCos120b[17]; Person *ptr2;

17 17 Initializing struct variables Date today = { 28, 11, 2014 }; Person peter = {“Miller”, ‘m’, 19, 3.48 };

18 18 Accessing struct members Date a, b, c[20], *ptr1; Direct component selection operator. (period) a.day=28; b.month=11; c[10].year=2014; Indirect component selection operator ─> ptr1 = &a; ptr1─>month = 4;

19 19 Structs within structs struct Dimension { int feet; float inches; }; struct Room { Dimension length, width; }; Room kitchen; kitchen.length.feet = 12; kitchen.length.inches = 2.4; kitchen.width.feet = 10; kitchen.width.inches = 1.8;

20 20 Functions returning structs struct Point { int x; int y; }; Point makepoint(int xvar, int yvar) { Point temp; temp.x = xvar;temp.y = yvar; return temp; } void main() { Point a, b; a = makepoint(0,0); b = makepoint(350,200);... }

21 21 Passing struct variables as arguments to functions struct Point { int x; int y; }; struct Rect { Point pt1, pt2; }; Pt1 – top left corner Pt2 – bottom right corner bool isPtinRect(Point p, Rect r) { returnp.x>=r.pt1.x && p.x<=r.pt2.x && p.y>=r.pt1.y && p.y<=r.pt2.y ; }

22 22 Functions with structs as arguments returning structs struct Point { int x; int y; }; Point addpoint( Point p1, Point p2) { Point temp; // alternate version temp.x = p1.x + p2.x; // p1.x = p1.x + p1.y; temp.y = p1.y + p2.y; // p1.y += p2.y; return temp; // return p1; } void main() { Point a, b, c;a=makepoint(0,0); b=makepoint(40, 20); c=addpoint(b,makepoint(20, 40));...}

23 23 Parallel arrays and arrays of structs Problem: data base for COS120 students t Solution based on parallel arrays: t Alternate solution: based on array of structures:

24 24 Parallel arrays and arrays of structs Problem: data base for COS120 students t Solution based on parallel arrays: char *name[20]; int id[20]; double gpa[20]; Three parallel arrays because data items with same subscript pertain the same student name[I] = “Peter”; id[I] = 0100245678; gpa[I] = 3.68;

25 25 Parallel arrays and arrays of structs Problem: data base for COS120 students t Alternate solution: based on array of structs: struct Stud{char *name; int id; double gpa;}; Stud ar[20];... ar[I].name = “Peter”; ar[I].id = 0100245678; ar[I].gpa = 3.68;

26 26 Pointers to structs struct Person { char *name, gender; int age;}; Person Mary, family[5], *ps; for (ps=family; ps<family+5; ps++) // or for (ps=&family[0]; ps<=&family[4]; ps++) { (*ps).name = …orps->name = … (*ps).gender = …or ps->gender = … (*ps).age = …or ps->age = … }

27 27 Pointers to Structs struct Electricity { string current; int volts; }; Electricity *p,*q; t p and q are pointers to a struct of type Electricity

28 28 Pointers to Structs p = new Electricity; t Allocates storage for struct of type Electricity and places address into pointer p t Struct access operator. ?? currentvoltsp

29 29 Assignments *p.current = “AC”; *p.volts = 115; t Statements above can also be written p -> current = “AC”; p -> volts = 115; AC115 currentvoltsp

30 30 Struct Member Access via Pointers t Form:p -> m t Example:p -> volts t Example: –cout current volts <<endl; t Output –AC115

31 31 Pointers to Structs q = new Electricity; t Allocates storage for struct of type Electricity and places address into pointer q t Copy contents of p struct to q struct *q = *p; AC115 q->currentq->voltsq

32 32 Pointers to Structs q->volts = 220; q = p; AC220 q->currentq->voltsq AC 115 AC220 q pq->currentq->volts p->currentp->volts

33 33 Unions A data structure that overlays components in memory, allowing one chunk of memory (the same memory cell or memory cells with same initial address) to be interpreted in multiple ways.

34 34 More on structs Extract from Friedman/Koffman, chapter 9

35 Data Structures Arrays and Structs Chapter 9

36 36 9.7 The Struct Data Type t struct used to store related data items t Individual components of the struct are called its members t Each member can contain different types of data t Employee example

37 37 Struct Employee // Definition of struct employee struct employee { int id; string name; char gender; int numDepend; money rate; money totWages; };

38 38 Employee variables // Definition of two struct employee variables employee organist, janitor;

39 39 Anonymous struct // Definition of anonymous struct struct { int id; string name; char gender; int numDepend; money rate; money totWages; } organist, janitor;

40 40 Accessing Members of a struct t Members are accessed using the member access operator, a period  For struct variable s and member variable m to access m you would use the following: –cout << s.m << endl; t Can use all C++ operators and operations on structs

41 41 Accessing Members of a struct organist.id = 1234; organist.name = “Noel Goddard”; organist.gender = ‘F’; organist.numDepend = 0; organist.rate = 6.00; organist.totWages += organist.rate * 40.0;

42 42 9.8 Structs as Operands and Arguments t How to do arithmetic and other operations using structs t Process entire struct using programmer defined functions t Often better to pass an entire struct rather than individual elements

43 43 Struct Copy or Assignment t struct copies Given employee struct employee organist, janitor; organist = janitor;

44 44 Passing struct as an Argument t Grading program example t Keep track of students grades t Prior to our learning structs we needed to store each item into a single variable t Group all related student items together t Pass struct by const reference if you do not want changes made

45 45 ExamStat.h // FILE: ExamStat.h struct examStats { string stuName; int scores[3]; float average; char grade; };

46 46 6 PrintStats.cpp // File: printStats.cpp Prints the exam statistics // Pre: The members of the struct variable // stuExams are assigned values. // Post: Each member of stuExams is displayed. void printStats(examStats stuExams) { cout << "Exam scores for " <<stuExams.stuName << ":\n“; cout << stuExams.scores[0] << ' ' << stuExams.scores[1] << ' ' << stuExams.scores[2] << endl; cout << "Average score: " <<stuExams.average << endl; cout << "Letter grade : " << stuExams.grade << endl; }

47 47 Common Programming Errors t No prefix to reference a struct member t Incorrect prefix reference to a struct member t Missing ; following definition of struct t Initialization of struct members

48 48 Exercise 26.1-26.7 Build programs based on structs: t Create a struct named Date to include three components all of int type – Day, Month and Year. Define three Date variables – D1, D2 and D3. D1 to be initialized. Load values for D2 using assignment statements and values for D3 entering input data from the keyboard. Display on the screen all members of the struct variables D1, D2, D3. t Create a struct named Time to include three components all of int type – Hrs, Mins and Scnds. Define three Time variables – T1, T2 and T3. T1 to be initialized. Load values for T2 using assignment statements and values for T3 entering input data from the keyboard. Display on the screen all members of the struct variables T1, T2, T3. t Create a struct named Person with data members for name, gender and age. Define struct variables describing data for your family. t Create a struct named Employee with data members for name, position and salary. Define struct variables describing data for five officers. t Create a struct named Student with data members for name, id# and e-mail address. Define struct variables describing data for your friends. t Create a struct to describe a 2D point in polar coordinates. t Create a struct to describe a 3D point in rectangular coordinates.

49 49 Homework 6 t Paper record to be presented before the end of next class t Tasks: –See.doc file.

50 50 Before lecture end Lecture: Structs More to read: Friedman/Koffman, Chapter 09

51 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Data Structs: Arrays and Structs Problem Solving, Abstraction, and Design using C++ 5e by Frank L. Friedman and Elliot B. Koffman

52 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 52 9.7 The struct Data Type struct used to store related data items Individual components of the struct are called its members Each member can contain different types of data Three parts –declaration of struct –use of struct to define a new variable –access of members of the structd variable Typically declare struct as global

53 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 53 struct Type Declaration struct struct-type { type 1 id-list 1 ; type 2 id-list 2 ;... type n id-list n ; }; struct employee { int id; string name; char gender; int numDepend; float rate; float totWages; };... employee organist, janitor;

54 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 54 Accessing Members of a struct organist.id = 1234; organist.name = “Noel Goddard”; organist.gender = ‘F’; organist.numDepend = 0; organist.rate = 12.00; organist.totWages = 480.0;... organist.totWages += (organist.rate * 40.0);

55 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 55 9.8 structs as Operands and Arguments struct copy or assignment organist = janitor; // copy janitor to organist Copies each member from janitor struct to organist struct

56 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 56 Passing a struct as an Argument Actual and formal parameters must be same type struct Using structs as arguments can shorten argument list Passing structs by value can be inefficient, since it duplicates values of all members

57 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 57 Passing struct by Reference Same as other reference parameters –use & to identify in parameter list Can also use constant reference –precede parameter with reserved word const –E.g. void printStats(const examStats& stuExams)

58 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 58 Listing 9.11 Function printStats

59 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 59 Listing 9.12 Function readEmployee

60 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 60 9.10 Common Programming Errors structs –References to a struct member with no prefix –Reference to a struct member no incorrect prefix –Missing semicolon following a struct declaration

61 61 Thank You For Your Attention


Download ppt "Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition."

Similar presentations


Ads by Google