Chapter 12 2 Arrays DaleWeems 1 Using Arrays

  • Slides: 29
Download presentation
Chapter 12 -2 Arrays Dale/Weems 1

Chapter 12 -2 Arrays Dale/Weems 1

Using Arrays as Arguments to Functions Generally, functions that work with arrays require 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 2

Example with Array Parameters #include <iomanip> #include <iostream> void Obtain (int[], int); // Prototypes

Example with Array Parameters #include <iomanip> #include <iostream> void Obtain (int[], int); // Prototypes here void Find. Warmest (const int[], int&); void Find. Average (const int[], int&); void Print (const int[], int); using namespace std; int main ( ) { // Array to hold up to 31 temperatures int temp[31]; int num. Days; int average; int hottest; int m; 3 3

Example continued cout << “How many daily temperatures? ”; cin >> num. Days; Obtain(temp,

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

Memory Allocated for Array int temp[31]; // Array to hold up to 31 temperatures

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

void Obtain ( /* out */ int temp[] , /* in */ int number

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 6

void Print ( /* in */ const int temp[], int number ) // Prints

void Print ( /* in */ const int temp[], 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 7

Use of const l Because the identifier of an array holds the base address

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 8

Use of const in prototypes Do not use const with outgoing array because function

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

void Find. Average( /* in */ const int temp[], /* in */ int number,

void Find. Average( /* 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 10 }

void Find. Warmest ( /* in */ const int temp[], /* in */ int

void Find. Warmest ( /* 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 11

Using arrays for Counters l Write a program to count the number of each

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

const int SIZE 91; int freq. Count[SIZE]; freq. Count[0] 0 freq. Count[1] 0 freq.

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

Main Module Pseudocode Level 0 Open data. File (and verify success) Zero out freq.

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

Counting Frequency of Alphabetic Characters // Program counts frequency of each alphabetic // character

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

int { main () ifstream data. File; int freq. Count[SIZE]; char ch; char index;

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

// Read file one character at a time data. File. get (ch); // Priming

// Read file one character at a time data. File. get (ch); // Priming read while (data. File) // While read successful { if (isalpha (ch)) { ch = if (islower (ch)) toupper (ch); freq. Count[ch] = freq. Count[ch] + 1; } data. File. get (ch); // Get next character } Print. Occurrences (freq. Count); return 0; } 17 17

void Print. Occurrences ( /* in */ const int freq. Count []) // Prints

void Print. Occurrences ( /* in */ const int freq. Count []) // Prints each alphabet character and its frequency // Precondition: // freq. Count[‘A’. . ‘Z’] are assigned // Postcondition: // freq. Count[‘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) << freq. Count[index] << endl; } 18 18 }

More about Array Indexes l Array indexes can be any integral type including char

More about Array Indexes l 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 It is the programmer’s responsibility to make sure that an array index does not go out of bounds The index value determines which memory location is accessed Using an index value outside this range causes the program to access memory locations outside the array l l l 19

Array with enum Index Type DECLARATION enum Department { WOMENS, CHILDRENS, LINENS, HOUSEWARES, ELECTRONICS

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

float sales. Amt[6]; sales. Amt[WOMENS] sales. Amt[CHILDRENS] sales. Amt[LINENS] (i. e. sales. Amt[0]) (i.

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

Parallel Arrays Parallel arrays are two or more arrays that have the same index

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 id. Number[SIZE]; float hourly. Wage[SIZE]; parallel arrays 22

const int SIZE 50; int id. Number[SIZE]; float hourly. Wage[SIZE]; // Parallel arrays hold

const int SIZE 50; int id. Number[SIZE]; float hourly. Wage[SIZE]; // Parallel arrays hold // Related information id. Number[0] 4562 hourly. Wage[0] 9. 68 id. Number[1] 1235 hourly. Wage[1] 45. 75 id. Number[2] 6278 hourly. Wage[2] 12. 71 . . . id. Number[48] 8754 hourly. Wage[48] 67. 96 id. Number[49] 2460 hourly. Wage[49] 8. 97 23

Array of Structures const enum int MAX_SIZE = 500; Health. Type { POOR, FAIR,

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

Animal. Type bronx. Zoo[MAX_SIZE]; bronx. Zoo [0] [1] . . . bronx. Zoo[0]. id

Animal. Type bronx. Zoo[MAX_SIZE]; bronx. Zoo [0] [1] . . . bronx. Zoo[0]. id 3456219 bronx. Zoo[0]. name “camel” bronx. Zoo[0]. genus “Camelus” bronx. Zoo[0]. species “dromedarius” bronx. Zoo[0]. country “India” bronx. Zoo[0]. age 10 bronx. Zoo[0]. weight 992. 8 bronx. Zoo[0]. health Fair [498] [499] 25

Animal. Type bronx. Zoo[MAX_SIZE]; . id bronx. Zoo[0] . name . genus . species

Animal. Type bronx. Zoo[MAX_SIZE]; . id bronx. Zoo[0] . name . genus . species . country. age. weight. health 3456219 “camel” “Camelus”“dromedarius” “India” 10 992. 8 Fair bronx. Zoo[1] bronx. Zoo[2] bronx. Zoo[3]. . . bronx. Zoo[498] bronx. Zoo[499] 26

Add 1 to the age member of each element of the bronx. Zoo array

Add 1 to the age member of each element of the bronx. Zoo array for (j = 0; j < MAX_SIZE; j++) bronx. Zoo[j]. age = bronx. Zoo[j]. age + 1; OR, for (j = 0; j < MAX_SIZE; j++) bronx. Zoo[j]. age++; 27

Find total weight of all elements of the bronx. Zoo array float total =

Find total weight of all elements of the bronx. Zoo array float total = 0. 0; for (j = 0; j < MAX_SIZE; j++) total += bronx. Zoo[j]. weight; 28

The End of Chapter 12 – Part 2 29

The End of Chapter 12 – Part 2 29