0% found this document useful (0 votes)
3 views

8. Lec8a_arrays

The document discusses arrays in programming, explaining their structure, declaration, and usage in C++. It highlights the challenges of handling dynamic input sizes and the need for arrays to store multiple values of the same type. Additionally, it covers accessing elements, limitations, and provides examples related to weather data manipulation and array reversal.

Uploaded by

degag64086
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

8. Lec8a_arrays

The document discusses arrays in programming, explaining their structure, declaration, and usage in C++. It highlights the challenges of handling dynamic input sizes and the need for arrays to store multiple values of the same type. Additionally, it covers accessing elements, limitations, and provides examples related to weather data manipulation and array reversal.

Uploaded by

degag64086
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 38

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

element 0 element 4 element 9

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];

 Each element initially gets a "zero-equivalent"


value.

Type Default value


int 0
double 0.0
bool false
string null
or other object (means, "no object")
6
Accessing elements
<name>[<index>] // access
<name>[<index>] = <value>; // modify
– Example:
numbers[0] = 27;
numbers[3] = -6;
cout<<numbers[0];
if (numbers[3] < 0) {
cout<<"Element 3 is negative.";
}
inde 0 1 2 3 4 5 6 7 8 9
x
value 27
0 0 0 -6
0 0 0 0 0 0 0
7
Arrays of other types
double results[5];
results[2] = 3.4;
results[4] = -0.5;
inde 0 1 2 3 4
x
value 0.0 0.0 3.4 0.0 -0.5

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

 Sometimes we assign each element a value in a loop.


for (int i = 0; i < 8; i++) {
numbers[i] = 2 * i;
}

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

int numbers[8] = { 0,2,4,6,8,10,12,14 };

int length = sizeof(numbers) /


sizeof(numbers[0])
inde 0 1 2 3 4 5 6 7
x
value 0 2 4 6 8 10 12 14

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

– Useful when you know what the array's elements


will be
– The compiler determines the length by counting the
values
16
"Array mystery" problem
 traversal: An examination of each element of an array.
 What element values are stored in the following array?

int a = { 1, 7, 5, 6, 4, 14, 11 };

int length = sizeof(a) / sizeof(a[0]);

for (int i = 0; i < length; i++) {

if (a[i] > a[i + 1]) {

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];

 You cannot compare arrays with ==


int a1 = {42, -7, 1, 15};
int a2 = {42, -7, 1, 15};
if (a1 == a2) { ... } // false!
 An array does not know how to print itself:
int a1 = {42, -7, 1, 15};
cout<<a1; // [I@98f8c4]

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.

Temperatures: [45, 44, 39, 48, 37, 46, 53]


Two coldest days: 37, 39
Two hottest days: 53, 48
19
Swapping values
void main() {
int a = 7;
int b = 35;
// swap a with b?
a = b;
b = a;
cout<<a << " " << b;
}
– What is wrong with this code? What is its output?

 The red code should be replaced with:


int temp = a;
a = b;
b = temp;
20
Array reversal question
 Write code that reverses the elements of an
array.
– For example, if the array initially stores:
[11, 42, -5, 27, 0, 89]

– Then after your reversal code, it should store:


[89, 0, 27, -5, 42, 11]

• The code should work for an array of any size.


• Hint: think about swapping various elements...
21
Algorithm idea
 Swap pairs of elements from the edges;
work inwards:
index 0 1 2 3 4 5
value 11
89 42
0 27
-5 27
-5 42
0 89
11

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.

int numbers []= {11, 42, -5, 27, 0, 89};


reverse(numbers);

– How do we write methods that accept arrays as


parameters?
– Will we need to return the new array contents after
reversal?
...
24
Array parameter (declare)
<type> <method>(<type>[] <name>) {

 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]

int* stutter(int numbers[], int length){


static int result[5];
for (int i = 0; i < length; i++) {
result[i] = 2*numbers[i];

}
return result;
}

27
Array return (call)
<type> *<name> = <method>(<parameters>);

 Example:

void main() {
int[] iq = {126, 84, 149, 167, 95};
int* stuttered = stutter(iq);

for(int i=0; i<len;i++)


cout << stuttered[i]<<" ";
}
...

 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];

// mat is a reference to the whole 2d array

// mat[0] or mat[r] are references to a single row

// mat[0][1] or mat[r][c] are references to


// single elements

// no way to refer to a single column

 How to determine the number of rows and


columns
32
2D Array Problems
 Write a method to find the max value in a 2d array of ints

 Write a method that finds the sum of values in each


column of a 2d array of doubles

 Write a method to print out the elements of a 2d array of


ints in row order.
– row 0, then row 1, then row 2 ...

 Write a method to print out the elements of a 2d array of


ints in column order
– column 0, then column 1, then column 2 ...
33
Reference Semantics

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.

You might also like