8. Lec8a_arrays
8. Lec8a_arrays
Slides based on material presented by Prof. Mike Scot University of Texas Austin
Can we solve this problem?
Consider the following program (input
underlined):
How many days' temperatures? 7
Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
Average temp = 44.6
4 days were above average.
2
Why the problem is hard
We need each input value twice:
– to compute the average (a cumulative sum)
– to count how many were above average
We could read each value into a variable...
but we:
– don't know how many days are needed until the
program runs
– don't know how many variables to declare
We need a way to declare many variables
in one step.
3
Arrays
array: object that stores many values of the
same type.
– element: One value in an array.
– index: A 0-based integer to access an element
from an array.
inde 0 1 2 3 4 5 6 7 8 9
x
value 12 49 -2 26 5 17 -6 84 72 3
4
Array declaration
<type> <name>[<length>];
– Example:
int numbers[10];
inde 0 1 2 3 4 5 6 7 8 9
x
valu 0 0 0 0 0 0 0 0 0 0
e
5
Array declaration, cont.
The length can be any non-negative integer.
int numbers[10];
bool tests[6];
tests[3] = true;
inde 0 1 2 3 4 5
x
value fals fals fals tru fals fals
e e e e e e
8
Out-of-bounds
Legal indexes: between 0 and the array's length - 1.
– Reading or writing any index outside this range will cause an error.
Example:
int data[10];
cout<<data[0]); // okay
cout<<data[9]); // okay
cout<<data[-1]); // exception
cout<<data[10]); // exception
inde 0 1 2 3 4 5 6 7 8 9
x
value 0 0 0 0 0 0 0 0 0 0
9
Accessing array elements
int numbers[8];
numbers[1] = 3;
numbers[4] = 99;
numbers[6] = 2;
int x = numbers[1];
numbers[x] = 42;
numbers[numbers[6]] = 11; // use numbers[6] as index
x 3
inde 0 1 2 3 4 5 6 7
x
numbers
value 0 3 11 42 99 0 2 0
10
Quick check
What is output by the following code?
string names[5];
names[1] = "Olivia";
names[3] = "Isabelle";
cout<<names[0].length();
A.no output due to null pointer exception
B.no output due to array index out of bounds exception
C.no output due to a compile error (code can't run)
D.0
E.6
11
Arrays and for loops
It is common to use for loops to access array elements.
for (int i = 0; i < 8; i++) {
cout<<numbers[i] << " ";
}
cout<<endl; // output: 0 3 11 42 99 0 2 0
inde 0 1 2 3 4 5 6 7
x
value 0 2 4 6 8 10 12 14
12
Arrays Length
How many elements array has or what is array length?
C++ does not have any inbuilt function for length
13
Weather question
Use an array to solve the weather problem:
How many days' temperatures? 7
Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
Average temp = 44.6
4 days were above average.
14
Weather answer
// Reads temperatures from the user, computes average and # days above average.
void main() {
const int days=7;
int temps[days]; // array to store days' temperatures
int sum = 0;
for (int i = 0; i < days; i++) {// read/store each day's temp
cout << "Day " << i + 1 << "'s high temp: ";
cin>> temps[i];
sum += temps[i];
}
float average = (float)sum / days;
int count = 0; // see if each day is above average
for (int i = 0; i < days; i++){
if (temps[i] > average)
count++;
}
printf("Average temp = %.1f\n", average);
cout << count << " days above average";
}
15
Quick array initialization
<type> <name> = {<value>, <value>, … <value>};
– Example:
int numbers[] = { 12, 49, -2, 26, 5, 17, -6 };
inde 0 1 2 3 4 5 6
x
value 12 49 -2 26 5 17 -6
int a = { 1, 7, 5, 6, 4, 14, 11 };
a[i + 1] = a[i + 1] * 2;
inde 0 1 2 3 4 5 6
x
value 1 7 10 12 8 14 22 17
Limitations of arrays
You cannot resize an existing array:
int a[4];
18
Weather question 2
Modify the weather program to print the
following output:
How many days' temperatures? 7
Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
Average temp = 44.6
4 days were above average.
22
Flawed algorithm
What's wrong with this code?
int numbers[] = {11, 42, -5, 27, 0, 89};
int length = sizeof(numbers)/sizeof(numbers[0]);
// reverse the array
for (int i = 0; i < length; i++) {
int temp = numbers[i];
numbers[i] = numbers[length - 1 - i];
numbers[length - 1 - i] = temp;
}
The loop goes too far and un-reverses the array! Fixed version:
for (int i = 0; i < length / 2; i++) {
int temp = numbers[i];
numbers[i] = numbers[length - 1 - i];
numbers[length - 1 - i] = temp;
}
23
Array reverse question 2
Turn your array reversal code into a reverse
method.
– Accept the array of integers to reverse as a parameter.
Example:
// Returns the average of the given array of numbers.
double average(int numbers[])
{
int length = sizeof(numbers) / sizeof(numbers[0]);
int sum = 0;
for (int i = 0; i < length; i++) {
sum += numbers[i];
}
return (double)sum / length;
}
– You don't specify the array's length (but you can examine it).
25
Array parameter (call)
<methodName>(<arrayName>);
Example:
void main() {
// figure out the average TA IQ
int iq[] = {126, 84, 149, 167, 95};
double avg = average(iq);
cout<<"Average IQ = " << avg;
}
...
– Notice that you don't write the [] when passing the array.
26
Array return (declare)
<type>* <method>(<parameters>) {
Example:
// Returns a new array with two copies of each value.
// Example: [1, 4, 0, 7] -> [1, 1, 4, 4, 0, 0, 7, 7]
}
return result;
}
27
Array return (call)
<type> *<name> = <method>(<parameters>);
Example:
void main() {
int[] iq = {126, 84, 149, 167, 95};
int* stuttered = stutter(iq);
Output:
[126, 126, 84, 84, 149, 149, 167, 167, 95, 95]
28
2D Arrays
29
29
2D Arrays in C++
Arrays with multiple dimensions may be
declared and used
int mat[3][4];
the number of pairs of square brackets
indicates the dimension of the array.
by convention, in a 2D array the first number
indicates the row and the second the column
30
Two Dimensional Arrays
0 1 2 3 column
0 0 0 0 0
1 0 0 0 0
2 0 0 0 0
row
This is our abstract picture of the 2D array and treating
it this way is acceptable.
(actual implementation is different)
mat[2][1] = 12;
31
What is What?
Int mat[10][12];
34
34
A swap method?
Does the following swap method work? Why or why
not?
void main() {
int a = 7;
int b = 35;
// swap a with b?
swap(a, b);
cout<<a << " " << b;
}
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
35
Value semantics
value semantics: Behavior where values are
copied when assigned, passed as parameters, or
returned.
– All primitive types in C++ use value semantics.
– When one variable is assigned to another, its value is
copied.
– Modifying the value of one variable does not affect
others.
int x = 5;
int y = x; // x = 5, y = 5
y = 17; // x = 5, y = 17
x = 8; // x = 8, y = 17
36
Reference semantics (objects)
reference semantics: Behavior where variables
actually store the address of a variable in memory.
– When one variable is assigned to another, the data is
not copied; both variables refer to the same object.
– Modifying the value of one variable will affect others.
int a1[] = {4, 15, 8};
int a2[] = a1; // refer to same array as a1
a2[0] = 7;
for (int i=0; i<len; i++)cout<<a1[i]; // [7, 15, 8]
inde 0 1 2
x
a1 a2
value 7
4 15 8
37
References and objects
Arrays use reference semantics. Why?
– efficiency. Copying large objects slows down a program.
– sharing. It's useful to share an object's data among
methods.