cse202: lecture 14the ohio state university1 arrays
TRANSCRIPT
CSE202: Lecture 14 The Ohio State University 2
Programming Problem
Write a program to:
• Read in a list of integers;
• Print the list in reverse order.
CSE202: Lecture 14 The Ohio State University 3
Arrays (1)
• So far the variables we have made store one value at a time. If you need to store and use 50 integers, then 50 int variables must be declared.
• These variables are called atomic or scalar, which means they cannot be further divided into smaller pieces.
CSE202: Lecture 14 The Ohio State University 4
One-Dimensional Arrays
• Instead of using 50 int variables, declare a single array which holds 50 int values.
• To declare an array for 50 int values, we use the following syntax:
int list[50];
• This creates an int array called list of size 50:
list
CSE202: Lecture 14 The Ohio State University 5
reverse.cpp... const int ARRAY_SIZE(5); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements
cout << "Enter list of " << ARRAY_SIZE << " integers: "; for (int i = 0; i < ARRAY_SIZE; i++) { cin >> list[i]; }
cout << "Reverse list: "; for (int i = ARRAY_SIZE-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl;...
CSE202: Lecture 14 The Ohio State University 6
... const int ARRAY_SIZE(5); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements
cout << "Enter list of " << ARRAY_SIZE << " integers: "; for (int i = 0; i < ARRAY_SIZE; i++) { cin >> list[i]; }
cout << "Reverse list: "; for (int i = ARRAY_SIZE-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl;...
> reverse.exeEnter list of 5 integers: 1 2 3 4 5Reverse list: 5 4 3 2 1
CSE202: Lecture 14 The Ohio State University 7
One-Dimensional Arrays (2)
• Examples of array declarations:
char name[40]; // 40 characters
double celsius[90]; // 90 doubles
bool flag[1000]; // 1000 true/false values
int list[50]; // 50 integers
list
• Note: Arrays are numbered starting at 0.
• The last element in array list of size 50 is list[49].
CSE202: Lecture 14 The Ohio State University 8
Other array declarations
• Use const int variables to declare arrays:
const int CELSIUS_ARRAY_SIZE(90);
double celsius[CELSIUS_ARRAY_SIZE];
// 90 doubles
const int MAX_LIST_LENGTH(50);
int list[MAX_LIST_LENGTH]; // 50 integers
CSE202: Lecture 14 The Ohio State University 9
Array Indices
• The list array from the the previous slide holds 50 integers.
list[0] refers to the first element in the array.
list[1] is the second element.
list[2] is the third element.
…
list[49] is the fiftieth element.
CSE202: Lecture 14 The Ohio State University 10
Using Array Variables
• Using array variables:
list[0] = 77; // assigns 77 to the first
// element in array list
list[1] = list[0];
list[2] = list[1] + 3;
// assigns 80 to list[2]
int i = 3;
list[2*i] = list[i-1] - list[i-2];
// assigns 3 to list[6]
CSE202: Lecture 14 The Ohio State University 11
More array indices
list[2*i] = list[i-1] - list[i-2];
• The array index can be specified using variables or expressions, but you must be careful of two things:– The variable or expression evaluates to an integer– The value is in the range of the array. In the list array
from the previous slide, the index range is something between 0 and 49.
CSE202: Lecture 14 The Ohio State University 12
Using a loop with arrays
• Arrays and for loops go hand-in-hand. Consider the following code:
const int SIZE(5);int a[SIZE];int b[SIZE];
// Note i = 0 and i < SIZEfor (int i = 0; i < SIZE; ++i){a[i] = 10;b[i] = 10*i;
} //What does this do?
CSE202: Lecture 14 The Ohio State University 13
aboveAverage.cpp // print out above average temperatures...int main{ const int TEMP_SIZE(6); double temp[TEMP_SIZE]; // array of TEMP_SIZE elements double sum(0.0), average(0.0);
// input temperatures cout << "Enter the temperature for the last " << TEMP_SIZE << " days: " << endl; for (int i = 0; i < TEMP_SIZE; i++) { cin >> temp[i]; }
CSE202: Lecture 14 The Ohio State University 14
aboveAverage.cpp (cont.) // compute the sum sum = 0.0; for (int i = 0; i < TEMP_SIZE; i++) { sum = sum + temp[i]; }
// compute the average average = sum/TEMP_SIZE;
// output above average temperatures cout << "Average temperature = " << average << endl; cout << "Above average temperatures: "; for (int i = 0; i < TEMP_SIZE; i++) { if (temp[i] > average) { cout << temp[i] << " "; } } cout << endl;
CSE202: Lecture 14 The Ohio State University 15
aboveAverage.cpp (cont.)... // output above average temperatures cout << "Average temperature = " << average << endl; cout << "Above average temperatures: "; for (int i = 0; i < TEMP_SIZE; i++) { if (temp[i] > average) { cout << temp[i] << " "; } } cout << endl;...
> aboveAverage.exeEnter the temperature for the last 6 days:10 20 30 40 50 60Average temperature = 35Above average temperatures: 40 50 60
CSE202: Lecture 14 The Ohio State University 16
aboveAverage.cpp (cont.)... // output above average temperatures cout << "Average temperature = " << average << endl; cout << "Above average temperatures: "; for (int i = 0; i < TEMP_SIZE; i++) { if (temp[i] > average) { cout << temp[i] << " "; } } cout << endl;...
> aboveAverage.exeEnter the temperature for the last 6 days:20 25 30 35 40 105Average temperature = 42.5Above average temperatures: 105
CSE202: Lecture 14 The Ohio State University 17
aboveAverage.cpp (cont.)... // output above average temperatures cout << "Average temperature = " << average << endl; cout << "Above average temperatures: "; for (int i = 0; i < TEMP_SIZE; i++) { if (temp[i] > average) { cout << temp[i] << " "; } } cout << endl;...
> aboveAverage.exeEnter the temperature for the last 6 days:62 65 60 54 22 58Average temperature = 53.5Above average temperatures: 62 65 60 54 58
CSE202: Lecture 14 The Ohio State University 18
logTableUnsafe.cpp (Unsafe)... const int TABLE_SIZE(10); double log_table[TABLE_SIZE]; // array of TABLE_SIZE elements int n;
cout << "Enter number of integers: "; cin >> n;
for (int i = 0; i < n; i++) { log_table[i] = log(double(i+1)); }
for (int i = 0; i < n; i++) { cout << "log(" << i+1 << ") = " << log_table[i] << endl; }...
CSE202: Lecture 14 The Ohio State University 19
logTableUnsafe.cpp (Unsafe)> logTableUnsafe.exeEnter number of integers: 5log(1) = 0log(2) = 0.693147log(3) = 1.09861log(4) = 1.38629log(5) = 1.60944
CSE202: Lecture 14 The Ohio State University 20
Why is this unsafe?... const int TABLE_SIZE(10); double log_table[TABLE_SIZE]; // array of TABLE_SIZE elements int n;
cout << "Enter number of integers: "; cin >> n;
for (int i = 0; i < n; i++) { log_table[i] = log(double(i+1)); }
for (int i = 0; i < n; i++) { cout << "log(" << i+1 << ") = " << log_table[i] << endl; }...
CSE202: Lecture 14 The Ohio State University 21
logTable.cpp... const int TABLE_SIZE(10); double log_table[TABLE_SIZE]; // array of TABLE_SIZE
elements int n;
cout << "Enter number of integers: "; cin >> n; while (n > TABLE_SIZE) { cout << "Input error.“; cout << " Input must be less than or equal to " << TABLE_SIZE << "." << endl;
cout << "Enter number of integers: "; cin >> n; }
CSE202: Lecture 14 The Ohio State University 22
logTable.cpp (cont.)
for (int i = 0; i < n; i++) { log_table[i] = log(double(i+1)); }
for (int i = 0; i < n; i++) { cout << "log(" << i+1 << ") = " << log_table[i] << endl; }
return 0;}
CSE202: Lecture 14 The Ohio State University 23
reverse2.cpp... const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(0);
cout << "Enter list of non-zero integers (ending with 0): "; cin >> x; num = 0; while (x != 0 && num < ARRAY_SIZE) { list[num] = x; num++; cin >> x; }
cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl;...
CSE202: Lecture 14 The Ohio State University 24
> reverse2.exeEnter list of non-zero integers (end list with 0): 1 2 3 -3 -2 -1 0Reverse list: -1 -2 -3 3 2 1
const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements ... cout << "Enter list of non-zero integers (ending with 0): "; cin >> x; num = 0; while (x != 0 && num < ARRAY_SIZE) { list[num] = x; num++; cin >> x; } ... cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; ...
CSE202: Lecture 14 The Ohio State University 25
> reverse2.exeEnter list of non-zero integers (end list with 0): -3 -2 -1 0 1 2 3 0Reverse list: -1 -2 -3
const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements ... cout << "Enter list of non-zero integers (ending with 0): "; cin >> x; num = 0; while (x != 0 && num < ARRAY_SIZE) { list[num] = x; num++; cin >> x; } ... cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; ...
CSE202: Lecture 14 The Ohio State University 26
> reverse2.exeEnter list of non-zero integers (end list with 0): 0Reverse list:
const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements ... cout << "Enter list of non-zero integers (ending with 0): "; cin >> x; num = 0; while (x != 0 && num < ARRAY_SIZE) { list[num] = x; num++; cin >> x; } ... cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; ...
CSE202: Lecture 14 The Ohio State University 27
What’s wrong with this program?... const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(0);
cout << "Enter list of non-zero integers (ending with 0): "; cin >> x; num = 0; while (x != 0) { list[num] = x; num++; cin >> x; }
cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl;...
CSE202: Lecture 14 The Ohio State University 28
What’s wrong with this program?... const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(0);
cout << "Enter list of non-zero integers (ending with 0): "; cin >> x; num = 0; while (x != 0 && n <= ARRAY_SIZE) { list[num] = x; num++; cin >> x; }
cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl;...
CSE202: Lecture 14 The Ohio State University 29
What’s wrong with this program?... const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(1);
cout << "Enter list of non-zero integers (ending with 0): "; num = 0; while (x != 0 && n < ARRAY_SIZE) { list[num] = x; num++; cin >> x; }
cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl;...
CSE202: Lecture 14 The Ohio State University 30
> reverse2Error3.exeEnter list of non-zero integers (end list with 0): 5 6 7 0Reverse list: 7 6 5 1
const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(1);
cout << "Enter list of non-zero integers (ending with 0): "; num = 0; while (x != 0 && num < ARRAY_SIZE) { list[num] = x; num++; cin >> x; } ... cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; ...
CSE202: Lecture 14 The Ohio State University 31
What’s wrong with this program?... const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(1);
cout << "Enter list of non-zero integers (ending with 0): "; num = 0; cin >> x; while (x != 0 && n < ARRAY_SIZE) { cin >> x; list[num] = x; num++; }
cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl;...
CSE202: Lecture 14 The Ohio State University 32
> reverse2Error4.exeEnter list of non-zero integers (end list with 0): 5 6 7 0Reverse list: 0 7 6
const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(0);
cout << "Enter list of non-zero integers (ending with 0): "; num = 0; while (x != 0 && num < ARRAY_SIZE) { cin >> x; list[num] = x; num++; } ... cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; ...
CSE202: Lecture 14 The Ohio State University 33
What’s wrong with this program?... const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(1);
cout << "Enter list of non-zero integers (ending with 0): "; num = 0; while (x != 0 && n < ARRAY_SIZE) { cin >> x; list[num] = x; num++; }
cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl;...
CSE202: Lecture 14 The Ohio State University 34
> reverse2Error5.exeEnter list of non-zero integers (end list with 0): 5 6 7 0Reverse list: 0 7 6 5
const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(1);
cout << "Enter list of non-zero integers (ending with 0): "; num = 0; while (x != 0 && num < ARRAY_SIZE) { cin >> x; list[num] = x; num++; } ... cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; ...
CSE202: Lecture 14 The Ohio State University 35
Array Initialization
• Arrays are initialized like scalar variables, except the list of values are placed in braces. For example:
int volts[5] = {2, 9, 100, 34, 27};char grades[3] = {‘a’, ‘c’, ‘b’};
• Initialization of large arrays can be split into 2 rows:
double states[10] = {5.4, 3.8, 3.4, 10.6, 9.2,1.8, 10.3, 14.0, 2.3,
1.4};
CSE202: Lecture 14 The Ohio State University 36
Array initialization (2)
• You do not have to initialize every element of an array:/* initializes hits[0], hits[1], and hits[2] to the values
indicated; all the rest are set to 0 */int hits[6] = {133, 25, 10001};
• The size of the array may be omitted if you initialized all of its values at declaration:
/* grades has three elements */int grades[] = {79, 90, 81};
/* same as above */int grades[3] = {79, 90, 81};
CSE202: Lecture 14 The Ohio State University 37
Linear Search Algorithm
• Array space[] = {7, 3, 6, 25, 3, 2, 75, 3, 5, 6};• Read input key;• Find location of key in array space[];• If key is in array space[], print:
“Found {key} at location {location}.”
• If key is not found, print:
“Sorry, we did not find {key}”.
CSE202: Lecture 14 The Ohio State University 38
linearSearch.cpp
. . .int main(){ const int SIZE(10); // array size int key(0); // search key (search for key) bool found(false); // flag for linear search
// search space (does not need to be in any order) int space[SIZE] = {7, 3, 6, 25, 3, 2, 75, 3, 5, 6};
// get search key from user cout << "Search for: "; cin >> key;. . .
CSE202: Lecture 14 The Ohio State University 39
linearSearch.cpp. . . for (int i = 0; i < SIZE; i++) { if (space[i] == key) { // found search key at location i cout << "Found " << key << " at location " << i<< endl; found = true; } }
if (!found) { cout << "Sorry, we did not find " << key << endl; }. . .
CSE202: Lecture 14 The Ohio State University 40
... int space[SIZE] = {7, 3, 6, 25, 3, 2, 75, 3, 5, 6};... for (int i = 0; i < SIZE; i++) { if (space[i] == key) { // found search key at location i cout << "Found " << key << " at location " << i<< endl; found = true; } }...
> linearSearch.exeSearch for: 2Found 2 at location 5> linearSearch.exeSearch for: 8Sorry, we did not find 8
What about 6?
What about 3?
CSE202: Lecture 14 The Ohio State University 41
Search for Duplicates Algorithm
• Read in input list;• for each element x in the list do:
– for each element y following x in the list do:• If (x == y), then print:
“Duplicate entry {location of x} = Entry {location of y} = y”;
CSE202: Lecture 14 The Ohio State University 42
duplicate.cpp// print duplicate entries in input list#include <iostream>using namespace std;
int main(){ const int SIZE(10); // array size int list[SIZE];
cout << "Enter list of " << SIZE << " integers: "; for (int i = 0; i < SIZE; i++) { cin >> list[i]; }
CSE202: Lecture 14 The Ohio State University 43
duplicate.cpp (cont.)
for (int i = 0; i < SIZE; i++) { for (int j = i+1; j < SIZE; j++) { if (list[i] == list[j]) { cout << "Duplicate entry " << i << " = Entry " << j << " = " << list[j] << endl; } } }
return 0;}
CSE202: Lecture 14 The Ohio State University 44
... for (int i = 1; i < SIZE; i++) { for (int j = i+1; j < SIZE; j++) { if (list[i] == list[j]) { cout << "Duplicate entry " << i << " = Entry " << j << " = " << list[j] << endl; } } } ...
• What does this output on input: 7 5 3 8 5 6 8 1 5 2?
CSE202: Lecture 14 The Ohio State University 45
Duplicates Algorithm: Version 2
• Read in input list;• for each element x in the list do:
– found_duplicate ← false;– for each element y following x in the list do:
• If ((x = y) and (found_duplicate = false)), then – Print:
“Duplicate entry {location of x} = Entry {location of y} = y”;
– found_duplicate ← true;
CSE202: Lecture 14 The Ohio State University 46
... for (int i = 1; i < SIZE; i++) { found_duplicate = false; for (int j = i+1; j < SIZE; j++) { if (list[i] == list[j] && !found_duplicate) { cout << "Duplicate entry " << i << " = Entry " << j << " = " << list[j] << endl; found_duplicate = true; } } } ...
• What does this output on input: 7 5 3 8 5 6 8 1 5 2?
CSE202: Lecture 14 The Ohio State University 47
Common Programming Errors
• Addressing indices that are out of bounds of the array range. This will run-time crash or at the very least a logical error. Be careful especially when using expressions to compute the indices.– Remember, indexing starts with 0, not 1!!!
• Forgetting to declare the array (either altogether or forgetting the [])
• Forgetting to initialize an array. Some compilers set everything to zero, some do not.
CSE202: Lecture 14 The Ohio State University 49
Linear Search Algorithm
• Array space[] = {7, 3, 6, 25, 3, 2, 75, 3, 5, 6};• Read input key;• Find the first location of key in array space[];• If key is in array space[], print:
“Found {key} at location {location}.”
• If key is not found, print:
“Sorry, we did not find {key}”.
CSE202: Lecture 14 The Ohio State University 50
Binary Seach
• Array list[] = {2, 3, 5, 6, 6, 7, 10, 12, 25, 75};
• Given a list in sorted order and a key:• Find a location of the key in the list.
CSE202: Lecture 14 The Ohio State University 51
Binary Search Algorithm
• Array list[] = (list[0], list[1], list[2], …, list[9])
• Input: key• Compare key to list[5];• If (key = list[5]), then “FOUND KEY!”;• If (key < list[5]), then search (list[0], list[1], …, list[4])• If (key > list[5]), then search (list[6], list[7], …, list[9])
CSE202: Lecture 14 The Ohio State University 52
Search (list[0], list[1], …, list[4])
• (list[0], list[1], list[2], …, list[4])
• Compare key to list[2];• If (key = list[2]), then “FOUND KEY!”;• If (key < list[2]), then search (list[0], list[1])• If (key > list[2]), then search (list[3], list[4])
CSE202: Lecture 14 The Ohio State University 53
Binary Search Algorithm
• (list[0], list[1], list[2], …, list[N-1])
• left ← 0;• right ← N-1;• While (key is not found) do
– midpoint ← (left + right)/2;– If (key = list[midpoint]), then “FOUND KEY!”;– If (key < list[midpoint]), then right ← midpoint-1;– If (key > list[midpoint]), then left ← midpoint+1;– If (right < left), then quit search; (key is not in list)
CSE202: Lecture 14 The Ohio State University 54
Binary Search Algorithm
• (list[0], list[1], list[2], …, list[N-1])
• left ← 0;• right ← N-1;• While (key is not found and left ≤ right) do
– midpoint ← (left + right)/2;– If (key = list[midpoint]), then “FOUND KEY!”;– If (key < list[midpoint]), then right ← midpoint-1;– If (key > list[midpoint]), then left ← midpoint+1;
CSE202: Lecture 14 The Ohio State University 55
binarySearch.cppint main(){ const int SIZE(10); // array size const key(0); // search for key int left(0), right(0), midpoint(0); // index array bool found(false); // flag found key
// this is an ORDERED LIST int list[SIZE] = {2, 3, 5, 6, 6, 7, 10, 12, 25, 75};
// get search key from user cout << "Search for: "; cin >> key;
...
CSE202: Lecture 14 The Ohio State University 56
binarySearch.cpp... left = 0; right = SIZE - 1; while (left <= right && !found) { midpoint = (left + right) / 2; // the floor (int division) if (key == list[midpoint]) { found = true; } // key is at midpoint else if (key < list[midpoint]) { right = midpoint - 1; } // consider left half of list else { left = midpoint + 1; } // consider right half of list } if (found) { cout << "Found " << key << " at location " << midpoint << endl; } else { cout << "Sorry, we did not find " << key << endl; }...