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.

Slides:



Advertisements
Similar presentations
Array. Convert Numbers in Different Base Systems Generate values to a series of numbers in different base systems: Base is between 2 and 9; Maximum number.
Advertisements

1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
1 Techniques of Programming CSCI 131 Lecture 24 Structs.
1 Chapter Structured Types, Data Abstraction and Classes Dale/Weems.
1 Lecture 10 Chapter 7 Functions 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.
Array What it is. How to use it How to declare it How to initialize it.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 Lecture 25 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
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 Techniques of Programming CSCI 131 Lecture 29 Search.
Chapter 7 Functions.
1 Chapter 7 Functions. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task l Using Function Arguments.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 Programming in C++ Dale/Weems/Headington Chapter 7 Functions.
1 Chapter 11 One-Dimensional Arrays. 2 Chapter 11 Topics l Atomic and composite data types l Declaring and instantiating an array l The length of an array.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
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 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
Chapter 8 Functions. Chapter 8 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task l Using Function Arguments.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Functions. 2 Chapter 7 Topics  Writing a Program Using Functional Decomposition  Writing a Void Function for a Task  Using Function Arguments and.
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.
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 7 Functions Dale/Weems/Headington. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task.
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 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:
Objective: Students will be able to: Declare and use variables Input integers.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
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.
1 Chapter 9 Scope, Lifetime, and More on Functions.
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.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
CS 1430: Programming in C++.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
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.
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)
Chapter 8 Functions.
Chapter 11 Arrays.
Lecture 7 1 Dimension Arrays Richard Gesick.
Dale/Weems/Headington
C++ Data Types Simple Structured Address Integral Floating
String in C++ A string is an array of characters which contains a non-printing null character ‘\0’ ( with ASCII value 0 ) marking its end. A string.
Chapter 9 Scope, Lifetime, and More on Functions
Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 11 Arrays.
CS150 Introduction to Computer Science 1
Chapter 8 Functions.
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
Presentation transcript:

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 The beginning memory address of the array (base address) n The number of elements to process in the array

3 #include void Obtain (int[], int); // Prototypes here void FindWarmest (const int[], int, int&); void FindAverage (const int[], int, int&); void Print (const int[], int); using namespace std; int main ( ) { // Array to hold up to 31 temperatures int temp[31]; int numDays; int average; int hottest; int m; Example with Array Parameters 3

4 cout << “How many daily temperatures? ”; cin >> numDays; Obtain(temp, numDays); // Call passes value of numDays and address temp cout << numDays << “ temperatures“ << endl; Print (temp, numDays); FindAverage (temp, numDays, average); FindWarmest (temp, numDays, hottest); cout << endl << “Average was: “ << average << endl; cout << “Highest was: “ << hottest << endl; return 0; } Example continued 4

5 Memory Allocated for Array temp[0] temp[1] temp[2] temp[3] temp[4]..... temp[30] 6000 Base Address int temp[31];// Array to hold up to 31 temperatures

6 void Obtain ( /* out */ int temp[], /* in */ int number ) // User enters number temperatures at keyboard // Precondition: // number is assigned && number > 0 // Postcondition: // temp[0.. number -1] are assigned { int m; for (m = 0; m < number; m++) { cout << “Enter a temperature : “; cin >> temp[m]; } 6

7 void Print ( /* in */ const int temp[], /* in */ int number ) // Prints number temperature values to screen // Precondition: // number is assigned && number > 0 // temp[0.. number -1] are assigned // Postcondition: // temp[0.. number -1] printed 5 per line { int m; cout << “You entered: “; for (m = 0; m < number; m++) { if (m % 5 == 0) cout << endl; cout << setw(7) << temp[m]; } 7

8 Use of const l Because the identifier of an array holds the base address of the array, an & is never needed for an array in the parameter list l Arrays are always passed by reference l To prevent elements of an array used as an argument from being unintentionally changed by the function, you place const in the function prototype and heading

9 Use of const in prototypes void Obtain (int[], int); void FindWarmest (const int[], int, int &); void FindAverage (const int[], int, int &); void Print (const int[], int); Do not use const with outgoing array because function is supposed to change array values use const with incoming array values to prevent unintentional changes by function

10 void FindAverage( /* in */ const int temp[], /* in */ int number, /* out */ int & avg) // Determines average of temp[0.. number-1] // Precondition: // number is assigned && number > 0 // temp[0.. number -1] are assigned // Postcondition: // avg == average of temp[0.. number-1] { int m; int total = 0; for (m = 0; m < number; m++) { total = total + temp[m]; } avg = int (float(total) / float(number) +.5); } 10

11 void FindWarmest ( /* in */ const int temp[], /* in */ int number, /* out */ int& largest) // Determines largest of temp[0.. number-1] // Precondition: // number is assigned && number > 0 // temp[0.. number -1] are assigned // Postcondition: // largest== largest value in temp[0.. number-1] { int m; largest = temp[0]; // Initialize to first element for (m = 0; m < number; m++) { if (temp[m] > largest) largest = temp[m]; } 11

12 Using arrays for Counters l Write a program to count the number of each alphabetic letter in a text file letterASCII ‘A’ 65 ‘B’ 66 ‘C’ 67 ‘D’ 68.. ‘Z’ 90 This is my text file. It contains many things! is not 14. Is it? A:\my.dat

13 const int SIZE 91; int freqCount[SIZE]; freqCount[0] 0 freqCount[1] 0.. freqCount[65] 2 freqCount[66] 0.. freqCount[89] 1 freqCount[90] 0 unused counts ‘A’ and ‘a’ counts ‘B’ and ‘b’. counts ‘ Y’ and ‘y’ counts ‘Z’ and ‘z’

14 Main Module Pseudocode Level 0 Open dataFile (and verify success) Zero out freqCount Read ch from dataFile WHILE NOT EOF on dataFile If ch is alphabetic character If ch is lowercase alphabetic Change ch to uppercase Increment freqCount[ch] by 1 Read ch from dataFile Print characters and frequencies

15 // Program counts frequency of each alphabetic // character in text file. #include const int SIZE=91; void PrintOccurrences(const int[]); // Prototype using namespace std; Counting Frequency of Alphabetic Characters

16 int main () { ifstream dataFile; int freqCount[SIZE]; char ch; char index; dataFile.open (“my.dat”); // Open if (! dataFile) // Verify success { cout << “ CAN’T OPEN INPUT FILE ! “ << endl; return 1; } for ( int m = 0; m < SIZE; m++) // Zero array freqCount[m] = 0; 16

17 // Read file one character at a time dataFile.get (ch); // Priming read while (dataFile) // While read successful { if (isalpha (ch)) { if (islower (ch)) ch = toupper (ch); freqCount[ch] = freqCount[ch] + 1; } dataFile. get (ch); // Get next character } PrintOccurrences (freqCount); return 0; } 17

18 void PrintOccurrences ( /* in */ const int freqCount []) // Prints each alphabet character and its frequency // Precondition: //freqCount[‘A’.. ‘Z’] are assigned // Postcondition: //freqCount[‘A’.. ‘Z’] have been printed { char index; cout << “File contained “ << endl; cout << “LETTER OCCURRENCES” << endl; for ( index = ‘A’ ; index < = ‘Z’; index ++) { cout << setw(4) << index << setw(10) << freqCount[index] << endl; } 18

19 More about Array Indexes Array indexes can be any integral type including char and enum types l The index must be within the range 0 through the declared array size minus one l It is the programmer’s responsibility to make sure that an array index does not go out of bounds l The index value determines which memory location is accessed l Using an index value outside this range causes the program to access memory locations outside the array

20 Array with enum Index Type DECLARATION enum Department { WOMENS, MENS, CHILDRENS, LINENS, HOUSEWARES, ELECTRONICS }; float salesAmt[6]; Department which; USE for (which = WOMENS; which <= ELECTRONICS; which = Department(which + 1)) cout << salesAmt[which] << endl; 20

21 float salesAmt[6]; salesAmt[WOMENS] (i. e. salesAmt[0]) salesAmt[MENS] (i. e. salesAmt[1]) salesAmt[CHILDRENS] (i. e. salesAmt[2]) salesAmt[LINENS] (i. e. salesAmt[3]) salesAmt[HOUSEWARES] (i. e. salesAmt[4]) salesAmt[ELECTRONICS] (i. e. salesAmt[5])

22 Parallel Arrays Parallel arrays are two or more arrays that have the same index range and whose elements contain related information, possibly of different data types EXAMPLE const int SIZE = 50; int idNumber[SIZE]; float hourlyWage[SIZE]; parallel arrays

23 const int SIZE 50; int idNumber[SIZE]; // Parallel arrays hold float hourlyWage[SIZE]; // Related information idNumber[0] 4562 hourlyWage[0] 9.68 idNumber[1] 1235 hourlyWage[1] idNumber[2] 6278 hourlyWage[2] idNumber[48] 8754 hourlyWage[48] idNumber[49] 2460 hourlyWage[49] 8.97

24 Array of Structures const int MAX_SIZE = 500; enum HealthType { POOR, FAIR, GOOD, EXCELLENT }; struct AnimalType // Declares struct type { long id; string name; string genus; string species; string country; int age; float weight; HealthType health; }; AnimalType bronxZoo[MAX_SIZE]; // Declares array 24

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 AnimalType bronxZoo[MAX_SIZE];.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 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 Find total weight of all elements of the bronxZoo array float total = 0.0; for (j = 0; j < MAX_SIZE; j++) total += bronxZoo[j].weight;

29 The End of Chapter 12 – Part 2