You are on page 1of 37

Containers -- Arrays

CS S CSIS1117 Computer Programming Co pute og a g

c1117 lecture 9

Contents

Arrays

Initialization Out of bound problem Pass index variables

Call-by-value Call by value Call-by-reference Multi-dimensional array

c1117 lecture 9

Storing a group of data

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

It seems to be troublesome to use 10 variables for storing the 10 numbers. g

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

See ten-variables-array.cc as an example


6

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]

Independent variables An array of elements

0 -3 -8 6

x[0] [0]

c1117 lecture 9

const declaration

To make programs more readable, we can use delcare constants:


const int SIZE=10; int x[SIZE]; for (int i=0; i<SIZE; i++) x[i]=0;

You Y can also use constant f common values: l t t for l


const const const const double PI=3.1415926; int NORMAL=0; int OVERWEIGHT=1; int OBESE=2;

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;

What is the output of the above code?

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

See array-init.cc as an example i it

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.

Write W it a program to read i 10 numbers and report t d in b d t the minimum of them.

We can declare an array with size 10 to store the 10 numbers.


int a[10];
12

c1117 lecture 9

Example

Use a loop to read the 10 numbers from user


for(int i = 0; i < 10; ++i) cin >> a[i];

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

Out of bound problem

Quite a number of program bugs are related to accessing a non-existence element of an array.

It is called the out-of-bound problem out of bound


int a[5] = {2, 3, 5, 7, 11}; for(int i = 0; i < 6 ++i) 0 6; cout << a[i] << endl;

What does a[5] contain?

Compiler cannot detect such problem


Will the program crash at run-time? Not necessary !! See out-of-bound.cc as an example
14

c1117 lecture 9

Out of bound problem


int myfunc(int x){ int p[5] = { -2, -3, -5, -7, -11 }; int q[5] = { 100, 101, 102, 103, 104 }; int a[5] = { 2, 3, 5, 7, 11 }; int total = 0; for (int i = 0; i < x; ++i){ total += a[i]; cout << a[i] << endl; a[i] = -a[i]; } // stepping on the toe of the other }

c1117 lecture 9

15

Pass indexed variables

An individual element of an array can be treated as a simple variable in passing to a function.


int smaller(int x, int y){ x You can treat it as if(x > y) return y; return x; an integer variable } and pass it to the int main(){ function smaller. int a[10]; for(int i = 0; i < 10; ++i) cin >> a[i]; int i i t min = a[0]; [0] for(int i = 0; i < 10; ++i) min = smaller(min, a[i]); }

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]

Scan the array one time and find the smallest


8 a[0] 4 1 9 7 2 0 6 5 3 a[9]

Swap this smallest element with the first element


0 4 a[0]
c1117 lecture 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]

Swap it with the element in the 2nd entry of the array


0 a[0] [0] 2 1 9 7 4 8 6 5 3 a[9] [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.

How we can sort the elements in programs? p g


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

If we want to write a function call swap to be used in the previous program

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]

a[0] swap(a[0], a[6]) 0 a[0]


c1117 lecture 9

3 a[9]

Exchange the element in l i position 0 with the element in position 6.

22

Example

How to write the swap function?


void swap(int p, int q){ int temp = p; p = q; q = temp; } int x = 10; int y = 20; cout << x << " " << y << endl; swap(x, y); cout << x << " " << y << endl; } 10 20 10 20

Why? What is the problem of the function?


c1117 lecture 9 23

Call by value Call-by-value


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

void swap(int p, int q){ int temp = p; p = q; q = temp; } swap(x, y); p( ,

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

void swap(int p, int q){ int temp = p; p = q; q = temp; } swap(x, y); p( ,

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

Call by reference Call-by-reference


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

An argument for a referent parameter should be a variable, see roots.cc as an example. i bl t l


27

c1117 lecture 9

void swap(int& p, int& q){ int temp = p; p = q; q = temp; } swap(x, y); p( ,

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

How to write the swap function?


void swap(int& p, int& q){ int temp = p; p = q; q = temp; } int x = 10; int y = 20; cout << x << " " << y << endl; swap(x, y); cout << x << " " << y << endl; } 10 20 20 10

See swap cc and simple-sort cc as examples. swap.cc simple-sort.cc examples


29

c1117 lecture 9

Passing arrays as arguments

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); }

10 3 4 8 21 -1 0 9 -32 2 10 Main memory

a, x

The array is passed by reference.


c1117 lecture 9

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); }

10 -32 32 3 4 8 21 -1 0 9 -32 10 2 10 Main memory

a, a x

Any changes of the values affect the original array.


c1117 lecture 9

size
34

Multi dimensional Multi-dimensional arrays

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

Two dimensional array


Mytable[0][0]

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

Same rule apply to pass argument in functions.


void print_multiarray(int a[][4], i t size){ id i t lti (i t [][4] int i ){ for(int i = 0; i < size; ++i) for(int j = 0; j < 80; ++j) cout << a[i][j]; }

c1117 lecture 9

37

You might also like