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

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by.
C Language.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Chapter 9 Data Structures: Arrays and Structs Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Data Structures Arrays and Structs Chapter The Array Data Type t Array elements have a common name –The array as a whole is referenced through.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 10: Pointers by.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Chapter 11 Structure and Union Types Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.
More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays.
User-defined Structure Types Structures: collection of data of different types. We can define a structure type student_t : typedef struct { string name;
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: Pointers.
Chapter 11 Structure. 2 Objectives You should be able to describe: Structures Arrays of Structures Structures as Function Arguments Dynamic Structure.
Chapter 11: Structured Data. Slide Introduction An array makes it possible to access a list or table of data of the same data type by using a single.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Lecture 9m: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Pointers and Dynamic Data Structures Problem Solving, Abstraction,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Pointers.
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11. The Struct Data Type.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by.
Chapter 9 Structured Data: Structs and ADTs (Data Base Programs with C++) Mr. Dave Clausen La Cañada High School.
Chapter 10 Introduction to Classes
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Lecture 25: Practical Training on Pointers. 2 Lecture Contents: t Reminder on Arrays t Reminder on Strings t Reminder on Pointers t Demo programs, Exercises.
1 Chapter 11 Structured Data. 2 Topics 10.1 Abstract Data Types 10.2 Combining Data into Structures 10.3 Accessing Structure Members 10.4 Initializing.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Structured Data Chapter 11. Combining Data Into Structures Structure: C++ construct that allows multiple variables to be grouped together Format: struct.
Structured Data Types struct class Structured Data Types array – homogeneous container collections of only one type struct – heterogeneous data type.
A FIRST BOOK OF C++ CHAPTER 16 DATA STRUCTURES. OBJECTIVES In this chapter, you will learn about: Single Structures Arrays of Structures Structures as.
Structures (aka records, structs) Textbook Chapter 11 sections:
Chapter 11 Structure and Union Types J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.
Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 8 Arrays.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
Pointer Variables int i; declares an int variable and sets aside a named memory location to store the int int * iptr; declares a variable that holds the.
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
1 CSC241: Object Oriented Programming Lecture No 05.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Struct Data Type in C++ What Are Structures?
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
chap11 Chapter 11 Structure and Union Types.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using for/while loops for sequential access t Demo programs.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
Lecture 10: Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Programming in C++ Dale/Weems/Headington Chapter 11 One-Dimensional Arrays.
Lecture 2 Arrays. Topics 1 Arrays hold Multiple Values 2 Accessing Array Elements 3 Inputting and Displaying Array Contents 4 Array Initialization 5 Using.
Lecture 04 Components of Programming Languages, Part III
Lecture 9 Structure 1. Concepts of structure Pointers of structures
Struct Data Type in C++ What Are Structures?
Structure (i.e. struct) An structure creates a user defined data type
Presentation transcript:

Lecture 26: Structures / struct s/

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 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 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 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 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 Struct definition (declaration) OR

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 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 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 Struct definition (declaration) struct specifier – no storage occupying sample struct Person { char name[20]; char gender; int age; float grade; };

12 Struct definition (declaration) OR

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

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

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 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 Initializing struct variables Date today = { 28, 11, 2014 }; Person peter = {“Miller”, ‘m’, 19, 3.48 };

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 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 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 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 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 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 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] = ; gpa[I] = 3.68;

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 = ; ar[I].gpa = 3.68;

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 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 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 Assignments *p.current = “AC”; *p.volts = 115; t Statements above can also be written p -> current = “AC”; p -> volts = 115; AC115 currentvoltsp

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

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 Pointers to Structs q->volts = 220; q = p; AC220 q->currentq->voltsq AC 115 AC220 q pq->currentq->volts p->currentp->volts

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 More on structs Extract from Friedman/Koffman, chapter 9

Data Structures Arrays and Structs Chapter 9

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 Struct Employee // Definition of struct employee struct employee { int id; string name; char gender; int numDepend; money rate; money totWages; };

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

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

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

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 Struct Copy or Assignment t struct copies Given employee struct employee organist, janitor; organist = janitor;

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 ExamStat.h // FILE: ExamStat.h struct examStats { string stuName; int scores[3]; float average; char grade; };

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 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 Exercise 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 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 Homework 6 t Paper record to be presented before the end of next class t Tasks: –See.doc file.

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

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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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

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;

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

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

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

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)

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

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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 Thank You For Your Attention