05 - Array
05 - Array
ARRAY
Programming Technique I
(SCSJ1013)
Array
Contents:
• Introduction
• Array Declaration
• Memory Layout
• Terminology
• Accessing Array Elements
• Array Initialization
• Processing Array Contents
• Array Assignment
• Arrays as Function Arguments
• Two-Dimensional Arrays
• Array of Strings
Introduction
• Array: variable that can store a collection of
data of the same type
– Examples: A list of names, A list of temperatures
• Why do we need arrays?
– Imagine keeping track of 5 test scores, or 100, or
1000 in memory
• How would you name all the variables?
• How would you process each of the variables?
Declaring an Array
• An array, named test, containing five
variables of type int can be declared as
int tests[5];
• The value in brackets is called
– A subscript
– An index
Array - Memory Layout
• The definition:
int tests[5];
allocates the following memory:
subscripts:
0 1 2 3 4
Accessing Array Elements
subscripts:
0 1 2 3 4
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 Elements - example
(Program Continues)
Accessing Array Elements - example
Here are the contents of the hours array, with the values
entered by the user in the example output:
Accessing Array Contents
Exercise 9.10
• Exercise (3) : Pg. 259
• Exercise (34 : Pg. 259 - pg. 260
No Bounds Checking in C++
• When you use a value as an array subscript,
C++ does not check it to make sure it is a valid
subscript.
• In other words, you can use subscripts that
are beyond the bounds of the array.
Example
• The following code defines a three-element
array, and then writes five values to it!
What the Code Does
No Bounds Checking in C++
• Be careful not to use invalid subscripts.
• Doing so can corrupt other memory locations,
crash program, or lock up computer, and
cause elusive bugs.
Array Initialization
• Arrays can be initialized with an initialization
list:
const int SIZE = 5;
int tests[SIZE] = {79,82,91,77,84};
• The values are stored in the array in the
order in which they appear in the list.
• The initialization list cannot exceed the array
size.
Example
Array Initialization
• Valid
int tests[3] = { 3, 5, 11 };
• Invalid
int tests[3];
tests= { 3, 5, 11 };
Partial Array Initialization
• If array is initialized with fewer initial values
than the size declarator, the remaining
elements will be set to 0:
Implicit Array Sizing
• Can determine array size by the size of the
initialization list:
int quizzes[]={12,17,15,11};
12 17 15 11
When this code is finished, the highest variable will contain the
highest value in the numbers array.
Finding the Lowest Value in an Array
int count;
int lowest;
lowest = numbers[0];
for (count = 1; count < SIZE; count++)
{
if (numbers[count] < lowest)
lowest = numbers[count];
}
When this code is finished, the lowest variable will contain the
lowest value in the numbers array.
Partially-Filled Arrays
• If it is unknown how much data an array
will be holding:
– Make the array large enough to hold the
largest expected number of elements.
– Use a counter variable to keep track of the
number of items stored in the array.
Comparing Arrays
• To compare two arrays, you must compare
element-by-element:
const int SIZE = 5;
int firstArray[SIZE] = { 5, 10, 15, 20, 25 };
int secondArray[SIZE] = { 5, 10, 15, 20, 25 };
bool arraysEqual = true; // Flag variable
int count = 0; // Loop counter variable
// Compare the two arrays.
while (arraysEqual && count < SIZE)
{
if (firstArray[count] != secondArray[count])
arraysEqual = false;
count++;
}
if (arraysEqual)
cout << "The arrays are equal.\n";
else
cout << "The arrays are not equal.\n";
In-Class Exercise
Given the following array definition:
int values[] = {2,6,10,14};
(Program Continues)
Parallel Array Example
(Program Continues)
Arrays as Function Arguments - example
Program 7-14 (Continued)
Modifying Arrays in Functions
• Array names in functions are like reference
variables – changes made to array in a
function are reflected in actual array in calling
function
• Need to exercise caution that array is not
inadvertently changed by a function
In-Class Exercise
• The following program skeleton, when completed, will ask the
user to enter 10 integers which are stored in an array. The
function avgArray, which you must write, is to calculate and
return the average of the numbers entered.
#include <iostream>
//Write your function prototype here
int main() {
const int SIZE = 10;
int userNums[SIZE];
cout << "Enter 10 numbers: ";
for (int count = 0; count < SIZE; count++){
cout << "#" « (count + 1) << " ";
cin >> userNums[count];
}
cout << "The average of those numbers is ";
cout << avgArray(userNUms, SIZE) << endl;
return 0;
}
//Write the function avgArray here.
In-Class Exercise
#include <iostream> void Test(int z[])
using namespace std; {
void Test(int []); int temp=z[3];
int main()
{
z[3]=z[0];
int myArr [4]={3,4,5,6}; z[0]=temp;
for(int i=0;i<4;i++)
cout<<myArr[i]<<" "; for(int j=0;j<4;j++)
cout<<endl; cout<<z[j]<<" ";
Test(myArr); }
cout<<endl;
for(int i=0;i<4;i++)
cout<<myArr[i]<<" ";
system("pause");
return 0;}
In-Class Exercise
#include <iostream> void Test(int num, int num1,
using namespace std; int z[])
void Test(int , int,int[]); {
int main() num=1001;
{ int x = 1; num1=290;
int y[3]; z[1]=34;
y[0]=1; z[2]=35;
Test(x,y[0],y); }
cout<<"x is: " << x<< endl;
cout<<"y[0] is: " <<y[0] <<
endl;
for(int i=0;i<3;i++)
cout<<y[i]<<endl;
system("pause");
return 0;}
In-Class Exercise
Each of the following definitions and program
segments has errors. Locate as many as you can and
correct the errors.
a) void showValues(int nums)
{
for(int i = 0; i<8; i++)
cout<<nums[i];
}
84 78
92 97
• Can omit inner { }, some initial values in a row
– array elements without initial values will be set
to 0 or NULL
Two-Dimensional Array as Parameter,
Argument
• Use array name as argument in function call:
getExams(exams, 2);
• Use empty [] for row, size declarator for column in
prototype, header:
const int COLS = 2;
// Prototype
void getExams(int [][COLS], int);
// Header
void getExams(int exams[][COLS], int rows)
Example – The showArray Function
from Program 7-19
How showArray is Called
Summing All the Elements in a Two-
Dimensional Array
Given the following definitions: