section 5 - arrays. problem solving often requires information be viewed as a “list” list may be...
TRANSCRIPT
Problem solving often requires information be viewed as a “list”
List may be one-dimensional or multidimensional
List is implemented by an array construct.
Array is a group of variables
- Same name and data type
- Variables are related in some way
- Most commonly used – multi-dimensional
- One-dimensional array
- Two-dimensional array
Arrays
Arrays allow you to store a number of similar type items but with asingle name.
• Array: variable that can store multiple values of the same type
• Values are stored in adjacent memory locations
• Declared using [] operator:
int tests[5];
This creates an array named tests with 5 elements (storage locations)
Array Terminology
In the definition int tests[5];
• int is the data type of the array elements
• tests is the name of the array
• 5, in [5], is the size declarator. It shows the number of elements in the array.
Array Declaration
element-type array-name [array-size];
Type of all the values in the array
Name of the entire collection of values
Integer expression indicating number of elements in the array
Declaring Array Variables
datatype arrayName[arraySize];
Example:
double myList[10];
C++ requires that the array size used to declare an array must be a constant expression.
For example, the following code is illegal:int size = 4;double myList[size]; // Wrong
But it would be OK, if size is a constant as follow:const int size = 4;double myList[size]; // Correct
Suppose
const int N = 20;
const int M = 40;
const int MaxStringSize = 80;
const int MaxListSize = 1000;
Then the following are all valid array definitions
int A[10]; // array of 10 ints
char B[MaxStringSize]; // array of 80 chars
double C[M*N]; // array of 800 floats
int Values[MaxListSize]; // array of 1000 ints
Array - Memory Layout
• The definition: int tests[5]; // size is 5 elements
allocates the following memory:
first element
second element
third element
fourth element
fifth element
Accessing Array Elements
• Each array element has a subscript, used to access the element.
• Subscripts start at 0
0 1 2 3 4Subscripts
Array Subscripts
• Enclosed in brackets ([ ])
• Indicates which element is referenced by position
• Array subscript value is different than array element value
• Subscript can be an expression of any integer type
• To be valid, subscript must be a value between 0 and one less than the array size
Accessing Array Elements
• Array elements can be used as regular variables: tests[0] = 79;cout << tests[0];cin >> tests[1];tests[4] = tests[0] + tests[1];
• Arrays must be accessed via individual elements:cout << tests; // not legal
Accessing Array Contents
• Can access element with constant subscript:cout << tests[3] << endl;
• Can use integer expression as subscript:for (i = 0; i < 5; i++)
cout << tests[i] << endl;
Suppose
int A[10]; // array of 10 int A[0], … A[9]
To access individual element must apply a subscript to list name A
A subscript is a bracketed expression also known as the index
First element of list has index 0
A[0]
Second element of list has index 1, and so on
A[1]
Last element has an index one less than the size of the list
A[9]
Incorrect indexing is a common error
A[10] // does not exist
Array Initialization
• List of initial values enclosed in braces ({ }) following assignment operator (=)
• Values from initialization list are assigned in order to array elements
• Length of initialization list cannot exceed size of the array
• Size of array can be automatically set to number of initializing values using empty brackets ([ ])
Initialization
element-type array-name [array-size] = {initialization-list};
float x[8] = {16.0, 12.0, 6.0, 8.0, 2.5, 12.0, 14.0, -54.5};
16.0 12.0 6.0 8.0 2.5 12.0 14.0 -54.5
double myList[4] = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following statements:
double myList[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
C++ allows you to omit the array size when declaring and creating an array using an initializer.
For example, the following declaration is valid
double myList[] = {1.9, 2.9, 3.4, 3.5};
C++ automatically figures out how many elements are in the array.
C++ allows you to initialize a part of the array.
For example, the following statement assigns values 1.9, 2.9 to the first two elements of the array.
The other two elements will be set to zero.
Note that if an array is declared, but not initialized, all its elements will contain “unkowns”, like all other local variables.
double myList[4] = {1.9, 2.9};
Access to Array Elements
• Random Access– Access elements is any order
• Sequential Access– Process elements in sequential order starting with the first
Displaying an Array
// List A of n elements has already been set
for (int i = 0; i < n; ++i) {cout << A[i] << " ";
}cout << endl;
Finding the smallest index of the largest element
double max = myList[0];int indexOfMax = 0;
for (int i = 1; i < ARRAY_SIZE; i++) { if (myList[i] > max) { max = myList[i]; indexOfMax = i; }}
#include <iostream>using namespace std;
int main(){ const int NUMBER_OF_ELEMENTS = 10; double numbers[NUMBER_OF_ELEMENTS]; double sum = 0;
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) { cout << "Enter a new number: "; cin >> numbers[i]; sum += numbers[i]; }
double average = sum / NUMBER_OF_ELEMENTS;
int count = 0; // The number of elements above average for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) if (numbers[i] > average) count++;
cout << "Average is " << average << endl; cout << "Number of elements above the average " << count << endl;
return 0;}
Example
Multidimensional Arrays
• Allows for complex arrangement of data• Can have many dimensions• Syntax
element-type arrayName [size1] [size2]…[sizen];
Exampledouble table[NROWS] [NCOLS];
Declaring Two- Dimensional Arrays
• Most common multidimensional array• Represents a table
Examplechar ticTacToe[3][3];
• AccessticTacToe[1][2]
Row
Column
Function sumMatrix
float sumMatrix (float table[NROWS][NCOLS]){
float sum = 0.0;
// Add each array element value to sum. for (int r = 0; r < NROWS; r++) for (int c = 0; c < NCOLS; c++) sum += table[r][c];
return sum;}
Example
const int NUM_ROWS = 11;const int SEATS_IN_ROW = 9;
string seatPlan [NUM_ROWS][SEATS_IN_ROW];
. . .
seatPlan[0][8] = “Gerry”;
Initialization
• Each inner pair of braces contains initial values for one row of the array matrix
const int NUM_ROWS = 2;const int NUM_COLS = 3;
float matrix[NUM_ROWS][NUM_COLS] ={{5.0, 4.5, 3.0}, {-16.0, -5.9, 0.0}};
Two-dimensional Array Illustration
[0] [1] [2] [3] [4]
[0]
7
[1] [2] [3] [4]
matrix[2][1] = 7;
int matrix[5][5];
7
int array[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };
1
2
3
4
5
6
8
9
10
11
12
[0] [1] [2] [3] [4] [0] [1] [2] [3]
[0] [1] [2] [3] [4]
[0] [1] [2] [3]
int array[4][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };
(a)
Equivalent
int array[4][3]; array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
(b)
Nested Loops for 2-D Arrays
• Row order– use row subscript as outer loop control variable
• Column order– use column subscript as outer loop control variable
Initializing Arrays with Random Values
The following loop initializes the array with random values between 0 and 99:
for (int row = 0; row < rowSize; row++) { for (int column = 0; column < columnSize; column++) { matrix[row][column] = rand() % 100; }}
Printing Arrays
To print a two-dimensional array, you have to print each element in the array using a loop like the following:
for (int row = 0; row < rowSize; row++) { for (int column = 0; column < columnSize; column++) { cout << matrix[row][column] << " "; } cout << endl;}
Summing Elements by Column
For each column, use a variable named total to store its sum. Add each element in the column to total using a loop like this:
for (int column = 0; column < columnSize; column++) { int total = 0;
for (int row = 0; row < rowSize; row++) total += matrix[row][column];
cout << "Sum for column " << column << " is " << total << endl;}
No Bounds Checking in C++
• C++ does not check if an array subscript is in the range of values for subscripts of the array
• Can access memory using subscripts that is before or after the memory for an array
• Can corrupt other memory locations, crash program, or lock up computer
• Need to be careful!