Containers Arrays Containers - Arrays: CSIS1117 Computer Programming CSS Co Pute Oga G
Containers Arrays Containers - Arrays: CSIS1117 Computer Programming CSS Co Pute Oga G
c1117 lecture 9
Contents
Arrays
c1117 lecture 9
In some situations, we need to keep track on situations many data items in the program for further processing. processing E.g. Write a program to read ten numbers, then return the mean and the standard deviation of them
We may need to use ten variables to keep the ten i bl numbers in the program. It is rather troublesome. See ten-variables cc as an example. ten-variables.cc example
c1117 lecture 9
int x1, x2, x3, x4, x5, x6, x7, x8, x9, x10; 1 2 3 6 8 9 10 cin >> x1 >> x2 >> x3 >> x4 >> x5 >> x6 >> x7 >> x8 >> x9 >> x10; double mean = (x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10) / 10.0; ) ; cout << "Mean: " << mean << endl; ... // calculate the standard deviation
How about write a program to read 100 numbers?? Create 100 variables?
c1117 lecture 9 4
Containers
A container is a collection of variables of the same type. The C++ built-in facility array is used for such built in purpose to form containers. To declare an array, we h T d l have to specify the t t if th type of the data and the maximum no. of data to be stored. t d
int score set[10]; score_set[10]; char myword[31]; // storing 10 int // storing 31 char
c1117 lecture 9
An array is a group of variables each of them variables, can be accessed using the subscript operator [].
int x[10]; double total = 0; const int max_no_input = 10; for(int i = 0; i < max no input; ++i){ max_no_input; cin >> x[i]; total += x[i]; } double mean = total / max_no_input; cout << "M t "Mean: " << mean << endl; dl ... // calculate the standard deviation
c1117 lecture 9
Similar to access the characters in a string the string, elements storing in an array with size n are accessing from index 0 to n-1. n 1.
8 x1 8 4 4 x2 1 x3 9 9 x4 0 x5 3 -2 x[9] [9]
0 -3 -8 6
x[0] [0]
c1117 lecture 9
const declaration
Note that constants are not variable. Their values cannot be changed.
8
c1117 lecture 9
Array initialization
Instead of assigning the values one by one the one, elements of an array can be initialized by a list of elements. elements
char choice[5]; choice[0] = 'A'; choice[1] = 'B'; h i [1] 'B' choice[2] = 'C'; choice[3] = 'D'; choice[4] = 'E'; char choice[] = {'A', 'B', 'C', 'D', 'E'}; { A , B , C , D , E };
The size can be omitted if it is equal to the no. of items i the list. it in th li t
9
c1117 lecture 9
Array Initialization
char choice[5] = {'A', 'B', 'C', 'D', 'E'}; { A , B , C , D , E }; cout << choice << endl;
It is a common error to print the array name instead of the elements in the array. Array of strings ay o st gs
string names[] = {"Peter", "Grace", "Mary", "David", "Timothy"}; David , Timothy }; int N = sizeof(names) / sizeof(names[0]); N = 5
10
c1117 lecture 9
sizeof(variable) return the actual memory size used to store the variable.
sizeof(names) si eof(names) the no of bytes used to store the whole array names. sizeof(names[0]) the no of bytes used to store a string. sizeof(names)/size(names[0]) the no of string elements in the array names. It can help to make the program more dynamic. p p g y
c1117 lecture 9
11
Example
string names[] = {"Peter" "Grace"}; {"Peter", int N = sizeof(names) / sizeof(names[0]); for(int i = 0; i < N; ++i){ ... }
The code of the for loop doesn't need to change if the size of the array names is changed.
c1117 lecture 9
Example
Traverse the array sequentially and keep the smallest y q y p value seen so far.
int min = a[0]; [ ] for(int i = 1; i < 10; ++i) if(min > a[i]) min = a[i];
The minimum value is kept in the variable min after the for loop.
13
c1117 lecture 9
Quite a number of program bugs are related to accessing a non-existence element of an array.
Will the program crash at run-time? Not necessary !! See out-of-bound.cc as an example
14
c1117 lecture 9
c1117 lecture 9
15
c1117 lecture 9
16
Example
Write a program to read in 10 numbers and print the numbers in ascending order.
Idea: Store the 10 numbers in an array and then sort array, the elements in the array with the smallest at the front and the largest at the end. g How to sort the elements? Find the smallest element and put it in the 1st entry of p y the array. Then find the 2nd smallest element and put it in the 2nd entry Until the end, the largest element is put in the last entry.
17
c1117 lecture 9
Example
Take the 10 numbers from input and store them in an array
8 a[0] 4 1 9 7 2 0 6 5 3 a[9]
3 a[9]
18
Example
Similarly, find the 2nd smallest element by scanning the array once
0 a[0] 4 1 9 7 2 8 6 5 3 a[9]
c1117 lecture 9 19
Example
Until the largest element is put at the end of the array
0 1 2 3 4 5 6 7 8 9 a[0] a[9] The elements in the array are sorted, and we only need to print them out one by one from the array array.
It can be done by using nested loops. Outer loop: scan from i=0 to 9, the i-th iteration locate the i-th smallest element and put it in the i-th entry. Inner loop: scan the array to locate the i-th smallest element. element
20
c1117 lecture 9
Example
index uses to store the index of the i-th smallest element in the i-th iteration.
for(int i = 0; i < 10; ++i){ ( ){ int index = i; for(int j = i + 1; j < 10; ++j) if(a[index] > a[j]) Scan the array from the index = j; int temp = a[index]; (i+1)-th elements to the last a[index] = a[i]; one in the i-th iteration and a[i] = temp; update the variable index if } a[index] is the smallest value among them. Swap the i-th smallest element with the element in i-th entry
c1117 lecture 9 21
Example
swap: takes two element values as arguments and exchange their values in the array.
8 4 1 9 7 2 0 6 5 3 a[9]
3 a[9]
22
Example
The variables x and y are called value parameters. p For value parameter, the argument is copied into the memory that belongs to the parameter. Any changes y g p y g of the value are only valid to the parameter variable but not the argument.
void swap(int x, int y){ int temp = x; p ; x = y; y = temp; } swap(x, y p y); 10 20 x y
c1117 lecture 9
Main memory
24
10 20 10 20 Main memory
x y p q
When the swap function is called, the values of variables x and y are copied to the local variables p and q in the swap function function.
c1117 lecture 9 25
10 20 20 10 10 Main memory
x y p q te p temp
Inside the swap function, only the local variables are updated but not x and y. The values of x and y are not changed after the execution of swap function function.
c1117 lecture 9 26
We can use reference parameter to solve the problem For reference parameter, the argument is the memory, the parameter is an alias for the argument memory memory.
For referencing the memory address of a variable, we add the symbol & in front of the variable variable.
void swap(int& p, int& q){ int temp = p; p = q; q = temp; }
c1117 lecture 9
10 20
x, p y, q
Main memory
When th Wh the swap f function i called, the local variables p ti is ll d th l l i bl and q are pointing to the same memory locations of x and y Any changes of them are also affect to x and y y. y.
c1117 lecture 9 28
Example
c1117 lecture 9
Can we pass the whole array as the argument to functions? Array in C++ can only be passed to functions by reference.
Usually the size of an array is also passed explicitly by y p p y y caller. We do not need to add & before the array variable.
void print_array(int a[], int size){ for(int i = 0; i < size; ++i) cout << a[i] << ' '; cout << endl; The number in the } bracket can be omitted. omitted
c1117 lecture 9
30
void sorting(int x[], int size){ for(int f (i t i = 0 i < size; ++i){ 0; i i){ int index = i; for(int j = i + 1; j < size; ++j) if(x[index] > x[j]) index = j; swap(x[index], swap(x[index] x[i]); } print_array(x,10);int main(){ } int a[10]; for(int i = 0; i < 10; ++i) cin >> a[i]; Input the array variable sorting(a, 10); as the argument return 0; }
c1117 lecture 9 31
int main(){ int a[10]; for(int i = 0; i < 10; ++i) cin >> a[i]; i [i] sorting(a, 10); return 0; }
10 3 4 8 21 -1 0 9 -32 2
10 3 4 8 21 1 0 9 32 2 Main memory
c1117 lecture 9
32
void sorting(int x[],int size){ for(int i=0; i<size; ++i){ int i d i t index = i; i for(int j=i+1; j<size; ++j) j if(x[index] > x[j]) index = j; swap(x[index], x[i]); } print_array(a); }
a, x
size
33
void sorting(int x[],int size){ for(int i=0; i<size; ++i){ int i d i t index = i; i for(int j=i+1; j<size; ++j) j if(x[index] > x[j]) index = j; swap(x[index], x[i]); } print_array(a); }
a, a x
size
34
We can declare array with two (or three four ) three, four, ) indexes. We call these kinds of arrays Multidimensional arrays. arrays A 2D array is just an array of array.
int mytable[3][8]; // A table with 3 rows and 8 columns
2D arrays are useful to implement table-like data object, e.g. matrix. object e g matrix
c1117 lecture 9
35
mytable t bl
Column
Row
Mytable[1][4] Mytable[2][7]
c1117 lecture 9 36
For multi dimensional array, the declaration must multi-dimensional array have bounds for all dimensions except the first one.
int mytable[][3] = { {1, 0, 4}, {-1, 1, 2}};
c1117 lecture 9
37