Chapter 7
Chapter 7
Chapter 7
Arrays
Objectives
• Use arrays to store, sort and search lists and tables of values
• Declare arrays, initialize arrays, and refer to the individual elements of arrays
• Pass arrays to functions
• Basic searching and sorting techniques
• Declare and manipulate multidimensional arrays
3
Arrays
• An array is a contiguous group of memory locations that have the same data type
• To refer to a particular location or element in the array: specify the name of the array
and the position number of the particular element
• The following figure shows an integer array called c
▫ The array c has 12 elements
▫ The position number is called a subscript or index (this number specifies the number of elements
from the beginning of the array)
▫ The first element in every array has subscript 0 (zero) and is sometimes called the zeroth element
[zero-based addressing]
▫ The highest subscript in array c is 11, which is 1 less than the number of elements in the array (12)
▫ A subscript must be an integer
4
5
6
Arrays
• As mentioned earlier, each element in an array can be called by giving the array
name followed by the element position in square brackets [ ] (also referred to as a
subscript)
• The first position is numbered 0
• For example, the elements in an array A that has three elements that can be
addressed by:
A[0] A[1] A[2]
7
Declaring arrays
• Arrays occupy space in memory
• To specify the type of the elements and the number of elements required by an array
use a declaration of the form:
arraytype arrayName; Example: int arr;
• The compiler reserves the appropriate amount of memory based on the type of the
elements and the arraySize
• Arrays can be declared to contain values of most data types
8
• Elements in the array C above are arranged from 0 to 9, the first element is C[0]
and the last is C[9]
• We can initialize the values of elements using the FOR loop:
int n[8] = { 32, 27, 64, 18, 95, 14, 90, 70};
• If the number of elements is unknown, we can omit the array size in the array
definition, it will be calculated automatically:
int n[] = {1, 2, 3, 4, 5};
Exercise: Declare an array n with 5 elements and initialize all elements with 0
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n[ 5 ]; // n is an array of 10 integers
OUTPUT
13
Exercise:
Declare an array n with 5 elements 32, 27, 64, 18, 95
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// use initializer list to initialize array n
int n[ 5 ] = { 32, 27, 64, 18, 95 };
} // end main
15
OUTPUT
16
Exercise:
Declare an array s with 10 elements. These elements are even integers from 2-20
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// constant variable can be used to specify array size
const int arraySize = 10;
int s[ arraySize ]; // array s has 10 elements
for ( int i = 0; i < arraySize; ++i ) // set the values
s[ i ] = 2 + 2 * i;
cout << "Element" << setw( 13 ) << "Value" << endl;
OUTPUT
19
int main()
{
const int arraySize = 10; // constant variable indicating size of array
int a[ arraySize ] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
int total = 0;
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int arraySize = 11;
OUTPUT
int n[ arraySize ] = {2, 7, 1, 4, 0, 9, 1, 2, 4, 2, 1}; Bar Chart of Array Elements
cout << “Bar Chart of Array Elements" << endl; 2 **
// for each element of array n, output a bar of the chart 7 *******
1 *
for ( int i = 0; i < arraySize; ++i ) 4 ****
{ 0
cout << n[i] << " "; 9 *********
1 *
// print bar of asterisks
2 **
for ( int stars = 0; stars < n[ i ]; ++stars ) 4 ****
cout << '*'; 2 **
1 *
cout << endl; // start a new line of output
} // end outer for
} // end main
22
• Reading from out-of-bounds array elements can cause a program to crash or even
appear to execute correctly while using bad data
OUTPUT
30
OUTPUT
32
int main()
{
cout << "First call to each function:\n";
staticArrayInit();
automaticArrayInit();
OUTPUT
37
#include <iostream>
using namespace std; // display results
if ( element != -1 )
int linearSearch(int [], int, int ); cout << "Found value in element " << element
// prototype << endl;
else
int main() cout << "Value not found" << endl;
{ } // end main
int arraySize = 100; // size of array a
int a[ arraySize ]; // create array a // compare key to every element of array until
int searchKey; // value to locate in array a // location is found or until end of array is
// reached; return subscript of element if key is
for ( int i = 0; i < arraySize; ++i ) // found or -1 if key not found
a[ i ] = 2 * i; // create some data int linearSearch(int array[], int key, int
sizeOfArray )
cout << "Enter integer search key: "; {
cin >> searchKey; for ( int j = 0; j < sizeOfArray; ++j )
if ( array[ j ] == key ) // if found
// attempt to locate searchKey in array a return j; // return location of key
int element = linearSearch( a, searchKey,
arraySize ); return -1; // key not found
} // end function linearSearch
39
Sorting an array
• Sorting data (i.e., placing the data into some particular order such as ascending or
descending) is one of the important computing applications
• A bank sorts all checks by account number so that it can prepare individual bank
statements at the end of each month
• Telephone companies sort their phone directories by last name and, within that by
first name, to make it easy to find phone numbers
40
Bubble Sort
• Bubble sort compares successive pairs of elements, swapping whenever the bottom
element of the pair is smaller than the one above it. In this way the smallest element
“bubbles up” to the top of the list
• The following program performs bubble sort
https://i.stack.imgur.com/XNbE0.gif
41
Multidimensional Arrays
• You can use arrays with two dimensions (i.e., 2D subscripts) to represent
tables of values consisting of information arranged in rows and columns
• To identify a particular table element, we must specify two subscripts
[row,column] by convention, the first identifies the element’s row and the
second identifies the element’s column
• Arrays with two or more dimensions are known as multidimensional arrays
43
Multidimensional Arrays
int main()
{
int matrix[3][4] = { {1,2,3,4},{5,6,7,8},{9,10,11,12} };
int main()
{
int a[3][4] = { {1,2,3,4},{5,6,7,8},{9,10,11,12} };
int total = 0;
for ( int row = 0; row < 3; ++row )
for ( int column = 0; column < 4; ++column )
total += a[ row ][ column ];
cout << “Sum of array elements is " << total << endl;
}
OUTPUT
Sum of array elements is 78
48
double d[ 2 ][ 10 ];
d[ 1, 9 ] = 2.345;
Error: d[1,9] has to be d[1][9]
int a[ 3 ]={5,10,15};
cout << a[ 1 ] << " " << a[ 2 ] << " " << a[ 3 ] << endl;
Error: we should write cout << a[ 0 ] << " " << a[ 1] << " " << a[ 2] << endl;