Organizing Heterogeneous Data Arrays allow a programmer to organize lists of values that are all of the same type (homogeneous). But we are often faced.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Modular Programming With Functions
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
True or false A variable of type char can hold the value 301. ( F )
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
1 9/08/06CS150 Introduction to Computer Science 1 Arithmetic Operators.
1 Midterm Review COMP 102. Tips l Eat a light meal before the exam l NO electronic devices (including calculators, dictionaries, phones, pagers, etc.)
Chapter 4 Making Decisions
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
C++ Programming Language Day 1. What this course covers Day 1 – Structure of C++ program – Basic data types – Standard input, output streams – Selection.
Multidimensional Arrays C++ also allows an array to have more than one dimension. For example, a two-dimensional array consists of a certain number of.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
1 Introduction to Arrays Problem: –Input 5 scores, compute total, average –Input Example –test scores,employees,temperatures.
1 Chapter 9 Scope, Lifetime, and More on Functions.
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
Chapter 6: Functions Starting Out with C++ Early Objects
Problem: A company employs a group of fifty salespersons (with reference numbers ) who are paid commission if their individual sales exceeds two-thirds.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Instructor - C. BoyleFall Semester
CPS120: Introduction to Computer Science
CPSC 252 Concrete Data Types Page 1 Overview of Concrete Data Types There are two kinds of data types: Simple (or atomic) – represents a single data item.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Arrays & Structures II Chapter 9. 2 Organizing Heterogeneous Data  Arrays allow a programmer to organize values of the same type  Homogeneous data 
Arrays Arrays in C++ An array is a data structure which allows a collective name to be given to a group of elements which all have.
Review Binary Numbers Bit : 0 or 1 Byte: 8 bites 256 different values 2 8 KB : 1024 bytes 2 10 bytes MB : 1024 * 1024 bytes 2 10 * 2 10 (2 20 ) bytes GB.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
8. Arrays Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Lists of Data A list is simply a sequence.
Quiz // // The function exchanges the two parameters. // Param: ( ) // Param:
More Array Access Examples Here is an example showing array access logic: const int MAXSTUDENTS = 100; int Test[MAXSTUDENTS]; int numStudents = 0;... //
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
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.
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
1 CS 1430: Programming in C++. 2 Find Max, Min, Average of m Sections Max, Min and Average of each section Max, Min and Average of all sections together.
Data Types Storage Size Domain of all possible values Operations 1.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
CS 1430: Programming in C++ 1. Test 2 Friday Functions Arrays For Loops Understand Concepts and Rules Memorize Concepts and Rules Apply Concepts and Rules.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
L what is a void-function? l what is a predicate? how can a predicate be used? l what is program stack? function frame? l what’s call-by-value? l what’s.
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
10. Structures Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Organizing Heterogeneous Data.
Bill Tucker Austin Community College COSC 1315
Basic concepts of C++ Presented by Prof. Satyajit De
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
New Structure Recall “average.cpp” program
Arrays, Part 1 of 2 Topics Definition of a Data Structure
One-Dimensional Array Introduction Lesson xx
CS 1430: Programming in C++ No time to cover HiC.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Fundamental Programming
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Presentation transcript:

Organizing Heterogeneous Data Arrays allow a programmer to organize lists of values that are all of the same type (homogeneous). But we are often faced with data values of differing types (heterogeneous) that are logically related, as we have seen earlier with trip data: OriginDestinationMilesTime Blacksburg, VAKnoxville, TN2443:25 Knoxville, TNNashville, TN1782:35 Nashville, TNMemphis, TN2103:17 Memphis, TNLittle Rock, AR1372:05 Little Rock, ARTexarkana, TX1412:10 While we can organize this data using parallel arrays, that is unsatisfying because we have then distributed the logically related values for a single trip across several different data structures. A better design would be to have a new data type Trip such that a variable of type Trip would contain all the related values for a single trip. The struct mechanism allows C++ programmers to do just that…

Structures struct Trip { string Origin; // starting point of trip string Destination; // ending point of trip int Miles; // distance traveled int Minutes; // time required, in min double MPH; // average speed }; Trip firstLeg; const int MAXLEGS = 100; Trip Itinerary[MAXLEGS]; // array of Trips structure-a heterogeneous collection of data values called members or fields -each member has a type and a unique name -individual members are accessed by name The definition of a structured type specifies the type name as well as the types and names of each of the members: Again, definitions of data types are almost always global since they are required throughout a program. The statement above does not declare a variable… it defines a type. As long as the type definition is in scope we may declare variables of that type in the usual way:

struct Variables A variable of a struct type will contain the values for all of the specified members for that type. Of course, the values of those members will just be random garbage until they have been properly initialized. Assuming we've initialized the members of the variable firstLeg, we would have a memory layout something like this: To reference a particular member of a struct variable, state the variable name followed by a period followed by the member name: Trip firstLeg; Blacksburg, VA Knoxville, TN firstLeg.Origin = "Blacksburg, VA"; firstLeg.Destination = "Knoxville, TN"; firstLeg.Miles = 244; firstLeg.Minutes = 205; firstLeg.MPH = 71.2; The period is called the member selector operator. In memory:

enum Color {RED, GREEN, BLUE, NOCOLOR}; struct Rectangle { Color Hue; int xNW, yNW; int Side[4]; };... Rectangle R; cin >> R.xNW >> R.yNW; cin >> R.Side[0] >> R.Side[1] >> R.Side[2] >> R.Side[3]; R.Hue = NOCOLOR; int Area = R.Side[0] * R.Side[1]; Member Access Example The members of a struct variable may be used just as if they were simple variables of the specified type.

Aggregate Operations Of course, the operations that are not supported by default may still be implemented via user- defined functions. An aggregate operation is an operation that is performed on a data structure, such as an structured variable, as a whole rather than performed on an individual member. Assume the following declarations: Trip X, Y; Assuming that both X and Y have been initialized, consider the following statements and expressions involving aggregate operations: X = Y; // _____ assigning one struct to another X == Y; // _____ comparing two structs with a relational operator cout << X; // _____ inserting an struct to a stream X + Y // _____ performing arithmetic with structs return X; // _____ using a struct as the return value from a function Foo(X); // _____ passing an entire struct as a parameter

struct Variables as Parameters void setMPH(Trip& aTrip) { aTrip.MPH = MINPERHOUR * double(aTrip.Miles) / aTrip.Minutes; } Entire struct variables can be passed to functions as parameters. By default is struct is passed by value. For example: void printTrip(ofstream& Out, const Trip& aTrip) { Out << left << setw(MAXNAMELENGTH + 1) << aTrip.Origin << setw(MAXNAMELENGTH + 1) << aTrip.Destination << right << setw(10) << aTrip.Miles << setw(10) << (aTrip.Minutes / MINSPERHOUR) << ':' << setfill('0') << setw(2) << (aTrip.Minutes % MINSPERHOUR) << setfill(' ') << setw(10) << setprecision(1) << aTrip.MPH << endl; } Since struct variables tend to be large, it is generally better to pass them by constant reference than by value if possible:

Implementing struct Operations bool areSame(const Trip& T1, const Trip& T2) { if ( (T1.Origin == T2.Origin) && (T1.Destination == T2. Destination) ) { return true; } return false; } Note that the meaning of equality for trips must be defined. Here we require the trips to have the same starting and ending points. Other definitions could also make sense; it depends on the context. A programmer can implement any needed operations that are not supported automatically: bool isFaster(const Trip& T1, const Trip& T2) { return (T1.MPH < T2.MPH); } Trip reverseTrip(const Trip& T) { Trip Reverse = T; Reverse.Origin = T.Destination; Reverse.Destination = T.Origin; return (Reverse); }

Problem n In a certain class (<=50 students) 3 programming assignments (worth 40%) and 3 tests (worth 60%) are given. All the programming and test scores must be in the range and should be checked for errors; otherwise the data is considered invalid. n Given an input file of unknown length, the task it to compute the average test and programming scores, and overall grades (A through F, based on 90, 80, 70, 60 scale) for each student, as well as class averages. n Assume that the data for each student consists of a SSN followed by 6 integers representing the programming and test scores.

Processing Student Grades const int MaxStudents=50; struct StudentType { string ssn; int P1, P2, P3, T1, T2, T3; float Pavg, Tavg, Overall; char grade; bool valid; }; StudentType students[MaxStudents]; SSNP1P2P3PavgT1T2T3TavgOverallGradeValid

initialize count priming read (1st SSN) while (infile) { read P1, P2, P3, T1, T2, T3 if (valid data) * { calculate Pavg, Tavg, Overall, grade * write out everything } else write “invalid data” update count read next SSN } numStudents = count calulate class averages (Prog, Test, Overall) * * opportunity for a function

cin >> students[i].ssn; cin >> students[i].P1 >> … >> students[i].T3; bool DataIsValid (StudentType stud) { if (any of 6 tests are invalid) return false; return true; }

void Averages (StudentType students[], int numStudents, double& progAvg, double& testAvg, double& overallAvg) { initialize sums and count for loop (using i) { if (students[i].valid) { update sums and count } calcuate averages }