1 Techniques of Programming CSCI 131 Lecture 24 Structs.

Slides:



Advertisements
Similar presentations
1 Chapter Structured Types, Data Abstraction and Classes Dale/Weems.
Advertisements

Dale/Weems/Headington
1 Chapter 12 Arrays Dale/Weems/Headington. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument.
1 Lecture 24 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Arrays and Other Data Structures 4 Introduction to Arrays 4 Bounds and Subscripts 4 Character Arrays 4 Integer Arrays 4 Floating Point Number Arrays 4.
1 C++ Plus Data Structures Nell Dale Chapter 2 Data Design and Implementation Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Chapter 9: Arrays and Strings
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 Lecture 25 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Chapter 8 Arrays and Strings
Dynamic Structures & Arrays.
1 Chapter 12 Arrays Dale/Weems/Headington. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument.
1 Lecture 22 Chapter 12 Arrays Dale/Weems/Headington.
1 Structured Types, Data Abstraction and Classes.
C++ Plus Data Structures Data Design and Implementation
Chapter 2 Data Design and Implementation. Data The representation of information in a manner suitable for communication or analysis by humans or machines.
1 C++ Plus Data Structures Nell Dale David Teague Chapter 2 Data Design and Implementation Slides by Sylvia Sorkin, Community College of Baltimore County.
1 Chapter 2 Data Design and Implementation. 2 Data The representation of information in a manner suitable for communication or analysis by humans or machines.
Arrays in C++ Numeric Character. Structured Data Type A structured data type is a type that stores a collection of individual components with one variable.
Chapter 8 Arrays and Strings
1 Chapter 10 Simple Data Types: Built-In and User- Defined.
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.
Chapter 10: Records (structs)
Cosc237/structures1 Structures aggregate data types record - single variable name for the whole collection composed of several variables - fields,BUT,
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Chapter 10 Simple Data Types: Built-In and User- Defined.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Lecture 19 Structs HW 5 has been posted. 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together.
Chapter 10 Simple Data Types: Built-In and User-Defined.
1 Data Structures and Algorithms Week 3 Data Abstraction: Part II Structured Types, and Classes.
1 Chapter 12-3 Arrays Dale/Weems. 2 Specification of Time class Time // “Time.h” { public : // 7 function members void Set (int hours, int minutes, int.
Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed.
1 Chapter 11 Arrays. 2 Chapter 11 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function.
1 Chapter 12-2 Arrays Dale/Weems. 2 Using Arrays as Arguments to Functions Generally, functions that work with arrays require 2 items of information n.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
1 Chapter 12 Arrays. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function.
1 Arrays. 2 Chapter 12 Topics  One-Dimensional Arrays  Using const in Function Prototypes  Using an Array of struct or class Objects  Using an enum.
Structures (aka records, structs) Textbook Chapter 11 sections:
1 Structural Types, Data Abstractions and Classes.
1 Chapter 12 Arrays Dale/Weems. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const.
1 Chapter 11 Arrays. 2 Chapter 11 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function.
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.
Fall 1999CS Composite Data Types. Fall 1999CS Topics to be Covered l Abstract data types l One-dimensional arrays l Two-dimensional arrays.
1 Chapter 12 Arrays Dale/Weems. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const.
Arrays.
Arrays Chapter 7. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
Module 1: Array ITEI222 - Advance Programming Language.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1 Chapter 12 Arrays Dale/Weems. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
ADVANCED POINTERS. Overview Review on pointers and arrays Common troubles with pointers Multidimensional arrays Pointers as function arguments Functions.
13/10/2016CS150 Introduction to Computer Science 1 Multidimensional Arrays  Arrays can have more than one column  Two dimensional arrays have two columns.
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.
1 Chapter 10 & 11 enum & Structured Types Dale/Weems.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
1 Structured Types, Data Abstraction and Classes.
Chapter 10 Simple Data Types: Built-In and User-Defined
Chapter 11 Arrays.
Chapter 2 Data Design and Implementation
Dale/Weems/Headington
C++ Data Types and Data Abstractions
Chapter 10 Simple Data Types: Built-In and User-Defined
Dale/Weems/Headington
Multi-Dimension Arrays
C++ Data Types and Data Abstractions
C++ Data Types Simple Structured Address Integral Floating
Chapter 11 Arrays.
Presentation transcript:

1 Techniques of Programming CSCI 131 Lecture 24 Structs

2 Arrays as Parameters Just as with a one-dimensional array, when a two- (or higher) dimensional array is passed as a parameter, the base address of the actual array is sent to the function. The size of all dimensions except the first must be included in the function heading and prototype. The sizes of those dimensions for the formal parameter must be exactly the same as in the actual array.

3 const int NUM_STATES = 50 ; const int NUM_MONTHS = 12 ; int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; int stateAverages [ NUM_STATES ] ; [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] Write a function using the two-dimensional stateHighs array to fill a one-dimensional stateAverages array Alabama Alaska Arizona [0] [1] [2]. [48] [49]

void findAverages(/*in*/ const int stateHighs[][NUM_MONTHS], /*out*/ int stateAverages[]) // PRE: stateHighs[ 0..NUM_STATES] [ 0..NUM_MONTHS] assigned // POST: stateAverages[ 0..NUM_STATES] contains rounded average // high temperature for each state { int state; int month; int total; for (state = 0; state < NUM_STATES; state++) { total = 0 ; for (month = 0; month < NUM_MONTHS; month++) total += stateHighs[state][month]; stateAverages[state] = int (total / ); } // for each state return; } // findAverages

5 Using typedef with Arrays Using typedef helps eliminate the chances of size mismatches between formal and actual parameters. FOR EXAMPLE, typedef int StateHighsType [ NUM_STATES ] [ NUM_MONTHS ] ; typedef int StateAveragesType [ NUM_STATES ] ; void findAverages( /* in */ const StateHighsType stateHighs, /* out */ StateAveragesType StateAverages ) {. }

6 Declaring Multidimensional Arrays EXAMPLE OF THREE-DIMENSIONAL ARRAY const NUM_DEPTS = 5 ; // mens, womens, childrens, electronics, furniture const NUM_MONTHS = 12 ; const NUM_STORES = 3 ; // White Marsh, Solomon Pond, Natick int monthlySales [NUM_DEPTS] [NUM_MONTHS] [NUM_STORES] ; rows columns sheets OR USING TYPEDEF typedef int MonthlySalesType [NUM_DEPTS] [NUM_MONTHS] [NUM_STORES] ; MonthlySalesType monthlySales;

const NUM_DEPTS = 5 ; // mens, womens, childrens, electronics, furniture const NUM_MONTHS = 12 ; const NUM_STORES = 3 ; // White Marsh, Solomon Pond, Natick int monthlySales [ NUM_DEPTS ] [ NUM_MONTHS ] [ NUM_STORES ] ; monthlySales[3][7][0] sales for electronics in August at White Marsh 12 MONTHS columns 5 DEPTS rows 3 STORES sheets

8 Print Sales for Each Month by Department COMBINED SALES FOR January DEPT # DEPT NAMESALES $ 0 Mens Womens Childrens Electronics Furniture COMBINED SALES FOR December DEPT # DEPT NAMESALES $ 0 Mens Womens Childrens Electronics Furniture 11230

const NUM_DEPTS = 5; // mens, womens, childrens, electronics, furniture const NUM_MONTHS = 12; const NUM_STORES = 3; // White Marsh, Solomon Pond, Natick int monthlySales [NUM_DEPTS] [NUM_MONTHS] [ NUM_STORES] ;.. for (month = 0; month < NUM_MONTHS; month++) { cout << “COMBINED SALES FOR ” ; WriteOut(month); // function call to write the name of month cout << “DEPT # DEPT NAMESALES $” << endl; for (dept = 0 ; dept < NUM_DEPTS ; dept++ ) { totalSales = 0; // sum over all stores for (store = 0; store < NUM_STORES; store++ ) { totalSales = totalSales + monthlySales [dept] [month] [store]; } // end for each store WriteDeptNameAndSales(dept, totalSales); // function call } // end for each department } // end for each month

10 Adding a Fourth Dimension const NUM_DEPTS = 5 ; // mens, womens, childrens, electronics, furniture const NUM_MONTHS = 12 ; const NUM_STORES = 3 ; // White Marsh, Solomon Pond, NatickCollection const NUM_YEARS = 2 ; int moreSales [NUM_DEPTS] [NUM_MONTHS] [NUM_STORES] [NUM_YEARS]; moreSales [3] [7] [0] [1] year 0year 1 for electronics, August, White Marsh, one year after starting year

11 C++ Data Types Structured Address pointer reference Simple IntegralFloating char short int long enum float double long double array struct union class

12 Limitations of Array Type In an array all elements (components) must be of the same type. For example, 20 chars or 52 floats or 100 strings. Often we have related information of various types that we’d like to store together for convenient access under the same identifier. For example...

13.id name.genus.species.country.age 18.weight health Good Example: thisAnimal 'g''i''a''n''t'' 'p''a''n''d''a'' \0'...'A''i''l''u''r''o'' 'p''o''d''a'' \0'...'m''e''i''a''n''o''l''e''k''a'' \0'...'C''h''i''n''a'' \0'...

14 anotherAnimal 6000.id name.genus.species.country.age 7.weight health Excellent 'L''a''m''a'' \0'... 'p''e''r''u''a''n''a'' \0' 'P''e''r''u'' \0'... 'l' 'a''m''a'' \0'...

15 Declaring a struct Type typedef char String20 [ 21 ] ; enum HealthType { Poor, Fair, Good, Excellent } ; struct AnimalType { // declares a struct data type // does not allocate memory long id ; String20 name ; String20 genus ; String20 species ; String20 country ; struct members int age ; float weight ; HealthType health ; } ; AnimalType thisAnimal ; // declare variables of AnimalType AnimalType anotherAnimal ;

16 General Form for struct Type Declaration SYNTAX struct TypeName { // does not allocate memory MemberList } ; MemberList SYNTAX DataType MemberName ;.

17 Declaring struct s The struct declaration names a type and names the members of the struct. It does not allocate memory for any variables of that type! You still need to declare your struct variables.

18 More About struct Type Declarations If the struct type declaration precedes all functions it will be visible throughout the rest of the file. If it is placed within a function, only that function can use it. It is common to place struct type declarations with TypeNames in a (.h ) header file and #include that file. It is possible for members of different struct types to have the same identifiers. Also a non-struct variable may have the same identifier as a structure member.

19 Accessing struct members Dot ( period ) is the member selection operator. After the struct type declaration, the various members can be used in your program only when they are preceded by a struct variable name and a dot. EXAMPLES thisAnimal.weight anotherAnimal.country

20 Operations on struct Members Valid operations on a struct member depend only on its type: thisAnimal.age = 18; thisAnimal.id = ; cin >> thisAnimal.weight; cin.get ( thisAnimal.species, 21 ); strcpy ( thisAnimal.name, “giant panda” ); thisAnimal.genus[0] = toupper (thisAnimal.genus[0] ); thisAnimal.age++; if (strcmp (thisAnimal.country, “Ceylon”) == 0) strcpy ( thisAnimal.country, “Sri Lanka” );

21 Aggregate struct operations I/O and comparisons of entire struct variables are NOT ALLOWED! Operations valid on an entire struct type variable: assignment to another struct variable of same type, pass to a function as parameter (by value or by reference), return as value of a function.

22 Examples of Aggregate struct Operations anotherAnimal = thisAnimal; // assignment WriteOut(thisAnimal); // value parameter ChangeWeightAndAge(thisAnimal); // reference parameter thisAnimal = GetAnimalData( ); // return value of function

23 Output of struct Member Values void WriteOut( /*in*/ AnimalType thisAnimal) // Prints out values of all members of thisAnimal // Precondition: all members of thisAnimal are assigned // Postcondition: all members have been written out { cout << “ID # “ << thisAnimal.id << thisAnimal.name << endl ; cout << thisAnimal.genus << thisAnimal.species << endl ; cout << thisAnimal.country << endl ; cout << thisAnimal.age << “ years “ << endl ; cout << thisAnimal.weight << “ lbs. “ << endl ; cout << “General health : “ ; WriteWord ( thisAnimal.health ) ; return; } // end WriteOut

24 Array of Structures typedef char String20 [ 21 ] ; const int MAX_SIZE = 500 ; enum HealthType { Poor, Fair, Good, Excellent } ; struct AnimalType { // declares struct data type long id ; String20 name ; String20 genus ; String20 species ; String20 country ; // 8 struct members int age ; float weight ; HealthType health ; } ; AnimalType bronxZoo [ MAX_SIZE ] ; // declares array

25 AnimalType bronxZoo[MAX_SIZE] bronxZoo [ 0 ] [ 1 ].. [ 498 ] [ 499 ] bronxZoo [ 0 ].id bronxZoo [ 0 ].name “camel” bronxZoo [ 0 ].genus “Camelus” bronxZoo [ 0 ].species “dromedarius” bronxZoo [ 0 ].country “India” bronxZoo [ 0 ].age 10 bronxZoo [ 0 ].weight bronxZoo [ 0 ].health Fair

26 bronxZoo[ ] array 19.id.name.genus.species.country.age.weight.health bronxZoo [ 0 ] “camel” “Camelus”“dromedarius” “India” Fair bronxZoo [ 1 ] bronxZoo [ 2 ] bronxZoo [ 3 ]. bronxZoo[498] bronxZoo[499]

27 Example Add 1 to the age member of each element of the bronxZoo[] array: for ( j = 0 ; j < MAX_SIZE ; j++ ){ bronxZoo[j].age = bronxZoo[j].age + 1 ; } OR, for ( j = 0 ; j < MAX_SIZE ; j++ ){ bronxZoo[j].age++ ; }

28 Example 2 Write the id and genus members of each element of bronxZoo[ ] from "China" : for ( j = 0 ; j < MAX_SIZE ; j++ ) { if (strcmp (bronxZoo[j].country, “China”) == 0 ) { cout << bronxZoo[ j ].id << bronxZoo[ j ].genus << endl ; } //is this animal from china? } //for each animal in the zoo

29 Example 3 Find the total weight of all elements of the bronxZoo[ ] array. float total = 0.0 ; for ( j = 0 ; j < MAX_SIZE ; j++ ){ total += bronxZoo[j].weight ; } //for each animal in the zoo