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

Containers - Arrays: CSIS1117 Computer Programming

The document discusses arrays in C++. It defines arrays as containers that store a group of data of the same type. Arrays can be initialized with a list of elements, and elements are accessed using indices in brackets. Common errors with arrays include accessing elements outside the bounds of the array. Arrays can be passed to functions by reference so that changes made in the function also affect the original array. The document provides examples of using arrays, including initializing them, sorting elements, and passing arrays to functions.

Uploaded by

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

Containers - Arrays: CSIS1117 Computer Programming

The document discusses arrays in C++. It defines arrays as containers that store a group of data of the same type. Arrays can be initialized with a list of elements, and elements are accessed using indices in brackets. Common errors with arrays include accessing elements outside the bounds of the array. Arrays can be passed to functions by reference so that changes made in the function also affect the original array. The document provides examples of using arrays, including initializing them, sorting elements, and passing arrays to functions.

Uploaded by

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

Containers -- Arrays

CSIS1117 Computer Programming

Contents

Arrays

Initialization
Out of bound problem
Pass index variables

Call-by-value
Call-by-reference
Multi-dimensional array
Command-line arguments

c1117 lecture 8

Storing a group of data

In some situations, we need to keep track on


many data items in the program for further
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


numbers in the program. It is rather troublesome.
See ten-variables.cc as an example.

c1117 lecture 8

int x1, x2, x3, x4, x5, x6, x7, x8, x9, x10;
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.

How about write a program to read 100 numbers??


Create 100 variables?
c1117 lecture 8

Containers

A container is a collection of variables of the same


type.
The C++ built-in facility array is used for such
purpose to form containers.
To declare an array, we have to specify the type
of the data and the maximum no. of data to be
stored.
int score_set[10];
char myword[31];

c1117 lecture 8

// storing 10 int
// storing 31 char

An array is a group of variables, each of them


can be accessed using the subscript operator [].

int x[10]; double total = 0;


const max_no_input = 10;
for(int i = 0; i < max_no_input; ++i){
cin >> x[i];
total += x[i];
}
double mean = total / max_no_input;
cout << "Mean: " << mean << endl;
...
// calculate the standard deviation

See ten-variables-array.cc as an example

c1117 lecture 8

Similar to access the characters in a string, the


elements storing in an array with size n are
accessing from index 0 to n-1.
8
x1
8

x[0]

c1117 lecture 8

4
x2

1
x3
9

9
x4

0 -3 -8 6

0
x5
3 -2
x[9]

Independent
variables
An array of
elements

Array initialization

Instead of assigning the values one by one, the


elements of an array can be initialized by a list of
elements.
char choice[5];
choice[0] = 'A';
choice[1] = 'B';
choice[2] = 'C';
choice[3] = 'D';
choice[4] = 'E';
char choice[] = {'A', 'B', 'C', 'D', 'E'};

The size can be omitted if it is equal to the no. of


items in the list.

c1117 lecture 8

Array Initialization
char choice[5] = {'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
string names[] = {"Peter", "Grace", "Mery",
"David", "Timothy"};
int N = sizeof(names) / sizeof(names[0]);
N = 5

See array-init.cc as an example

c1117 lecture 8

sizeof(variable) return the actual memory size


used to store the variable.

sizeof(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 makes the program more flexible.

c1117 lecture 8

10

Example
string names[] = {"Peter", "Grace"};
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 is changed.

Write a program to read in 10 numbers and report


the minimum of them.

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


numbers.
int a[10];

c1117 lecture 8

11

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


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.

c1117 lecture 8

12

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


int a[5] = {2,
for(int i = 0;
cout << a[i]

3, 5, 7, 11};
i < 6; ++i)
<< endl;

What a[5] contains?

Compiler cannot detect such problem

Will the program crash at run-time?


Not necessary !! See out-of-bound.cc as an example

c1117 lecture 8

13

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){
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 min = a[0];
for(int i = 0; i < 10; ++i)
min = smaller(min, a[i]);
}

c1117 lecture 8

14

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


the elements in the array with the smallest at the front
and the largest at the end.
How to sort the elements?
Find the smallest element and put it in the 1st entry of
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.

c1117 lecture 8

15

Example
Take the 10 numbers from input and store them in an array
8

a[0]

3
a[9]

Scan the array one time and find the smallest


8 4
a[0]

3
a[9]

Swap this smallest element with the first element


0 4
a[0]
c1117 lecture 8

3
a[9]
16

Example
Similarly, find the 2nd smallest element by
scanning the array once
0

a[0]

3
a[9]

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


0

a[0]

3
a[9]

c1117 lecture 8

17

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.

How we can sort the elements in programs?

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.

c1117 lecture 8

18

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
one in the i-th iteration and
a[index] = a[i];
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 8

19

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

3
a[9]

3
a[9]

swap(a[0], a[6])
0 4
a[0]
c1117 lecture 8

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

20

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 8

21

Call-by-value

The variables x and y are called value parameters.


For value parameter, the argument is copied into the
memory that belongs to the parameter. Any changes
of the value are only valid to the parameter variable
but not the argument.
Memory
void swap(int x, int y){
int temp = x;
x = y;
y = temp;
}
swap(x, y);

c1117 lecture 8

address
1004
1008
...

10
20

1300
1304
1308
Main memory
22

void swap(int p, int q){


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

Memory
address
1004
1008
...
1300
1304

10
20

10

20

1308
Main memory

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.
c1117 lecture 8

23

void swap(int p, int q){


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

Memory
address
1004
1008
...
1300
1304

10
20

20

10
10

1308
temp
Main memory

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.
c1117 lecture 8

24

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.
For referencing the memory address of a variable, we add
the symbol & in front of the 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.

c1117 lecture 8

25

void swap(int& p, int& q){


int temp = p;
p = q;
q = temp;
}

Memory
address
1004

10

x, p

1008

20

y, q

1012
1016

swap(x, y);

1020
Main memory

When the swap function is called, the local variables p


and q are pointing to the same memory locations of x
and y. Any changes of them are also affect to x and y.
c1117 lecture 8

26

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.

c1117 lecture 8

27

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


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.

c1117 lecture 8

28

void sorting(int x[], int size){


for(int i = 0; i < size; ++i){
int index = i;
for(int j = i + 1; j < size; ++j)
if(x[index] > x[j])
index = j;
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 8

29

Memory address
10
1004
3
1008
int main(){
4
1012
int a[10];
8
1016
for(int i = 0; i < 10; ++i)
21
cin >> a[i];
-1
1020
sorting(a, 10);
0
return 0;

9
}
-32
2
10 3 4 8 21 1 0 9 32 2

c1117 lecture 8

Main memory

30

Memory address
10
1004
void sorting(int x[],int size){
3
1008
for(int i=0; i<size; ++i){
4
int index = i;
1012
8
for(int j=i+1; j<size; ++j)
1016
21
if(x[index] > x[j])
-1
index = j;
1020
swap(x[index], x[i]);
0

}
9
print_array(a);
-32
}
2

The array is passed by reference.


c1117 lecture 8

10
Main memory

a, x

size
31

Memory address
10 -32
1004
void sorting(int x[],int size){
3
1008
for(int i=0; i<size; ++i){
4
int index = i;
1012
8
for(int j=i+1; j<size; ++j)
1016
21
if(x[index] > x[j])
-1
index = j;
1020
swap(x[index], x[i]);
0

}
9
print_array(a);
-32 10
}
2

Any changes of the values affect


the original array.
c1117 lecture 8

10
Main memory

a, x

size
32

Multi-dimensional arrays

We can declare array with two (or three, four, )


indexes. We call these kinds of arrays Multidimensional 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.

c1117 lecture 8

33

Two dimensional array


Mytable[0][0]

mytable

Column

Row

Mytable[1][4]
Mytable[2][7]
c1117 lecture 8

34

For multi-dimensional array, the declaration must


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], int size){
for(int i = 0; i < size; ++i)
for(int j = 0; j < 80; ++j)
cout << a[i][j];
}

c1117 lecture 8

35

Command-line arguments

Our program begins to run in the main function.


We can modify the parameter list of main so that it
can accept input from the user.

e.g. filename for the input file used in the program

The first parameter should be of type int and the


second one is char ** (what is it??)

You will learn it later, it is more important to learn how


to use it.
int main(int argc, char * argv[]){
...
}

c1117 lecture 8

36

Suppose the executable of our program is called


prog and is invoked as follows in the command
prompt:
prog 9 test.txt

Then argc is 3, which is the number of arguments plus


the program name.
argv[0] contains prog
argv[1] contains 9
argv[2] contains test.txt.
See prog.cc as an example

c1117 lecture 8

37

Each argv[i] is a string literal, not a string


variable. We cannot use member function of string
in this case.
Error !!
cout << argv[0].length() << endl;

We can instead assign the argv[i] to a string


variable, e.g.
string name = argv[0];
cout << name.length() << endl;

Moreover, program may crash if it accesses


argv[i] for i >= argc.

c1117 lecture 8

38

You might also like