h4 Array
h4 Array
Cecia Chan
Brian Mak
Dimitris Papadopoulos
Pedro Sander
Charles Zhang
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.1
What is an Array?
Array is a collection of
homogeneous objects: objects
of the same type. e.g., a
collection of int, char, double,
. . ., or user-defined types.
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.2
Motivation from Programming Point of View
A function to sort 3 integers can be:
void sort 3 int(int& x, int& y, int& z);
A function to sort 6 integers can be:
void sort 6 int(int& u, int& v, int& w, int& x, int& y, int& z);
How about a function to sort 10,000 integers? Are you going
to create variable names for the 10,000 different integers?
Array is designed to solve this problem: you only need one
identifier name to address all the 10,000 integers, and there is
a way to refer to each of them.
It can solve problems like: read a list of student names, and
sort them in alphabetical order.
In an Excel file, each column/row is basically an array so that
you can do some common operations (like average, max, min,
count) on it.
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.3
Part I
1-Dimensional Array
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.4
C++ 1-Dimensional Array
Examples
int number[10000]; // An array of 10,000 uninitialized integers
int n = 3;
double x[n]; // Compilation error on VC++: size is NOT a constant
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.5
Subscripting: Access to Each Array Element
Examples
int y; // A regular int variable
int x[3]; // An array of 3 int numbers
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.7
Example: Manipulate an Array of Scores using for Loop
int main()
{
const int NUM_STUDENTS = 5;
float score[NUM_STUDENTS];
float sum_score = 0.0; // Don’t forget initializing the sum
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.8
Example: Manipulate an Array of Scores using for Loop ..
#include <iostream> /* array-max.cpp */
using namespace std;
int main()
{
const int NUM_STUDENTS = 5;
float score[NUM_STUDENTS];
// Read in the first student’s score. Assume #students >= 1
cin >> score[0];
float max_score = score[0]; // A good way to initialize max score
When the codes are run, x[-2] = 5; will put the value 5 to
the memory space which is 2 × 4 bytes (size of 2 int) before
the array x. Similarly, x[100] = 9; will put the value 9 to the
memory space which is 90 × 4 bytes beyond the array.
This is a common cause of the run-time error called
segmentation fault — your program trespasses into memory
locations that may not belong to it.
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.10
Array Initialization
Just like any local variable, when an array is defined, its
elements are not initialized automatically.
If there are fewer values than the array size, the unspecified
values will be zeros.
It is a compilation error if there are more values than the array
size.
If you leave out the array size in the array initialization, the
compiler will count the number of initializing values and uses
that as the array size.
Once defined, you cannot assign values to an array using the
initialization syntax.
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.11
Example: Array Initialization
int a[5];
a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; a[4] = 5;
*/
// Compilation error:
// can’t assign values to an array using the { } syntax
e = {5, 6, 7};
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.12
Common Mis-uses of an Array
While each array element can be treated as a simple variable, the
whole array, as represented by the array identifier, cannot.
Examples: Correct and Incorrect Uses of Arrays
int x[] = {1, 2, 3, 4, 5 };
int y[] = {6, 7, 8, 9, 0 };
int z[5];
/* Incorrect way */
// Cannot assign to array elements using the initialization syntax
x = {5, 4, 3, 2, 1};
Since the array identifier alone does not tell us about its size,
a function that operates on an array needs at least 2 input
arguments:
the array identifier
the array size (of type int)
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.14
Example: Pass an Array to a Function
int main()
{
const int NUM_STUDENTS = 5;
float score[NUM_STUDENTS];
cout << "mean score = " << mean_score(score, NUM_STUDENTS) << endl;
cout << "max score = " << max_score(score, NUM_STUDENTS) << endl;
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.17
Example: Modifying Array’s Elements by a Function
int main()
{
int a[] = {1, 2, 3, 4};
int b[] = {11, 12, 13, 14};
int c[4];
array_add(a, b, c, 4);
array_print(c, 4);
cout << endl;
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.19
Example: Return-by-Value vs. Return-by-Reference
#include <iostream> /* random-element.cpp */
#include <cstdlib>
using namespace std; /* To return a random array element */
int main()
{
srand(time(0)); // Seed the random num generator
int data[6] = {10, 20, 30, 40, 50, 60};
cout << element_rbv(data, 6) << endl; // Same as: cout << data[?]
cout << element_rbr(data, 6) << endl; // Same as: cout << data[?]
print_array(data, 6);
element_rbr(data, 6) += 8; // Same as: data[?] += 8
print_array(data, 6);
}
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.20
Constant Array
It defines 4 integer constants: x[0], x[1], x[2], and x[3] are all
of the type const int.
Like simple constants, a constant array
must be initialized when it is defined.
once defined, its elements cannot be modified.
One main use of constant array is in the definition of the
formal parameters of a function: to disallow modification of
the elements of an array passed to a function, declare that
array constant using const.
inside the function, the array is read-only.
however, the original array in the caller is still writable.
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.21
Example: Prevent Modification by Constant Array
int main()
{
const int NUM_STUDENTS = 5;
float score[NUM_STUDENTS];
cout << "mean score = " << mean_score(score, NUM_STUDENTS) << endl;
cout << "max score = " << max_score(score, NUM_STUDENTS) << endl;
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.23
Part II
Multi-dimensional Array
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.24
Array of any Dimensions
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.25
C++ 2-dimensional Array
COLUMN
0 1 2 a[0][0] 1000
1
1004
a[0][1] 2
0 a[0][0] a[0][1] a[0][2] 1008
ROW
a[0][2] 3
1012
a[1][0] 4
1 a[1][0] a[1][1] a[1][2] 1016
a[1][1] 5
6 1020
a[1][2]
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.26
Initialization of 2D Array
A 2D array can be initialized in 2 ways:
row by row, or
like a 1D array since the array cells are actually stored linearly
in the memory.
Examples
/* Initialize row by row */
int point[5][2] = { // An int array with 5 rows and 2 columns
{1, 1},
{2, 4},
{3, 9},
{4, 16},
{5, 25}
};
/*
* Initialize using the fact that the cells of a 2D
* array actually are stored linearly in the memory
*/
int point[5][2] = { 1,1, 2,4, 3,9, 4,16, 5,25 };
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.27
Previous Example: Euclidean Distance
#include <iostream> /* File: distance-fcn.cpp */
#include <cmath> // Math library info
using namespace std;
cout << " AB = " << euclidean_distance(xA, yA, xB, yB) << endl;
cout << " BC = " << euclidean_distance(xB, yB, xC, yC) << endl;
cout << " CA = " << euclidean_distance(xC, yC, xA, yA) << endl;
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.28
Example: Compute Distance with 2D Array
#include <iostream> /* File: 2d-array-fcn.cpp */
#include <cmath>
using namespace std;
void compute_all_distances(
const float point[][2], float dist[][3], int num_points)
{
for (int i = 0; i < num_points; i++)
for (int j = 0; j < num_points; j++)
dist[i][j]
= euclidean_distance(point[i][0], point[i][1],
point[j][0], point[j][1]);
}
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.29
Example: Compute Distance with 2D Array ..
void print_2d_array(const float a[][3], int num_rows, int num_columns)
{
for (int i = 0; i < num_rows; i++)
{
for (int j = 0; j < num_columns; j++)
cout << a[i][j] << ’\t’;
cout << endl;
}
}
int main()
{
float dist[3][3]; // Distances between any pairs of points
float point[3][2] // (x, y) coordinates of 3 points
= { {1.0, 1.0} , {2.0, 2.0} , {4.0, 3.0} };
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.30
Better Example: Compute Distance with 2D Array
/* File: 2d-array-fcn2.cpp
* Each row of a 2D array, e.g., a[N][M], can be treated as a 1D array.
* The i-th row can be addressed as a[N],
* which represents a 1D array of M elements.
*/
void compute_all_distances(
const float point[][2], float dist[][3], int num_points)
{
for (int i = 0; i < num_points; i++)
for (int j = 0; j < num_points; j++)
dist[i][j] = euclidean_distance(point[i], point[j]);
}
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.31
C++ N-dimensional Array
Syntax: Definition of an N-dimensional Array
<data-type> <array-name> [<size1 >] [<size2 >] · · · [<sizeN >] ;
x
a[1][0][0] a[1][0][1]
a[0][0][0] 1000
1
1004
a[0][0][1] 2
a[1][1][0] a[1][1][1]
1008
a[0][1][0] 3
a[0][0][0] a[0][0][1]
1012
0 a[0][1][1] 4
1016
a[1][0][0] 5
a[0][1][0] a[0][1][1] 6 1020
1 a[1][0][1]
y 1024
a[1][1][0] 7
0 1 1028
z a[1][1][1] 8
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.32
Remarks on Multi-dimensional Array
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.33
Part III
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.34
C String
In general, one cannot deal with the whole array at once, but
has to deal with each array element, one at a time because a
sequence of, e.g., integers, do not represent a new object.
Just add the null character ’\0’ (ASCII code = 0) after the
last character of the string you need.
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.35
C String ..
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.36
Example: C String
#include <iostream> /* File: c-string.cpp */
using namespace std;
int main()
{
char s1[6] = {’h’, ’k’,’u’,’s’,’t’, ’z’};
int main()
{
char a[20] = "Albert";
char b[20] = "Einstein";
char c[20];
int length;
return 0;
} // Read Appendix B of the textbook for more C string library functions.
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.39
Example: Functions with 2D Character Array
#include <iostream> /* File: str-array.cpp */
using namespace std;
int main()
{
// 5 C-strings, each having a max. length of 15 char
const char word[5][16] = {
"hong kong",
"university",
"of",
"science",
"technology"
};
print_strings(word, 5);
return 0;
}
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.40
Reading C Strings with cin
cin will skip all white spaces before reading data of the
required type until it sees the next white space.
White spaces are any sequence of ’ ’, ’\t’ and ’\n’.
For char x; cin x; , if the input is “ hkust ”, cin will
skip all the leading white spaces, and gives ’h’ to x.
The same is true for reading a C string.
For char x[20]; cin x; , if the input is “ hkust ”, cin
will skip all the leading white spaces, and gives “hkust” to x.
Thus, cin is not good at reading multiple words or even a
paragraph including possibly the newline. Instead, use:
cin.getline(char s[ ], int max-num-char, char terminator);
cin.getline( ) will stop when either (max-num-char - 1)
characters are read, OR, the terminating character terminator
is seen. The terminating character is removed from the input
stream but is not read into the string.
The C-string terminating null character is automatically
inserted at the end of the read string.
{ kccecia, mak, dipapado, psander, charlesz }@cse.ust.hk COMP2011 (Fall 2022) p.41
Example: Palindrome
#include <iostream> /* File: palindrome.cpp */
using namespace std;
int main() {
const int MAX_LINE_LEN = 255; char whole_line[MAX_LINE_LEN+1];