6 Arrays
6 Arrays
Slide 2
Learning Objectives
Introduction to Arrays
Declaring and referencing arrays
For-loops and arrays
Arrays in memory
Arrays in Functions
Arrays as function arguments, return values
Programming with Arrays
Partially Filled Arrays, searching, sorting
Multidimensional Arrays
Slide 3
Introduction to Arrays
Array definition:
A collection of data of same type
First ‘aggregate’ data type
Means ‘grouping’
int, float, double, char are simple data types
Used for lists of like items
Test scores, temperatures, names, etc.
Avoids declaring multiple simple variables
Can manipulate ‘list’ as one entity
Slide 4
Declaring Arrays
Declare the array allocates memory
int score[5];
Declares array of 5 integers named ‘score’
Similar to declaring five variables:
int score[0], score[1], score[2], score[3], score[4]
Individual parts called many things:
Indexed or subscripted variables
‘Elements’ of the array
Value in brackets called index or subscript
Numbered from 0 to size - 1
Slide 5
Accessing Arrays
Access using index/subscript
cout << score[3];
Note two uses of brackets:
In declaration, specifies SIZE of array
Anywhere else, specifies a subscript
Size, subscript need not be literal
int score[MAX_SCORES];
score[n+1] = 99;
If n is 2, identical to: score[3]
Slide 6
Array Usage
Powerful storage mechanism
Can issue command like:
“Do this to ith indexed variable”
where i is computed by program
“Display all elements of array score”
“Fill elements of array score from user input”
“Find highest value in array score”
“Find lowest value in array score”
Slide 7
Array Program Example 1
#include <iostream>
using namespace std;
int main()
{
int N1[5],N2[5];
N1[2]=4;
N1[0]=N1[2];
N2[4]=N1[0];
system ("pause");
return 0;
}
Array Program Example 2
#include <iostream>
using namespace std;
int main()
{
int max, score[5];
cout<<"Enter 5 scores"<<endl;
for(int index=0;index<5;index++)
cin>>score[index];
max=score[0];
for(int index=1;index<5;index++)
{
if(max<score[index])
max=score[index];
}
cout<<"the highest score is "<<max;
system("pause");
return 0;
}
Slide 9
for-loops with Arrays
Natural counting loop
Naturally works well ‘counting thru’ elements
of an array
Example:
for (idx = 0; idx<5; idx++)
{
cout << score[idx] << endl;
}
Loop control variable (idx) counts from 0 – 5
Slide 10
Major Array Pitfall
Array indexes always start with zero!
Zero is ‘first’ number to computer
scientists
C++ will ‘let’ you go beyond range
Unpredictable results
Compiler will not detect these errors!
Up to programmer to ‘stay in range’
Slide 11
Major Array Pitfall Example
Indexes range from 0 to (array_size – 1)
Example:
double temperature[24]; // 24 is array size
// Declares array of 24 double values called
temperature
They are indexed as:
temperature[0], temperature[1] … temperature[23]
Common mistake:
temperature[24] = 5;
Index 24 is ‘out of range’!
No warning, possibly disastrous results
Slide 12
Defined Constant as Array Size
Always use defined/named constant for
array size
Example:
const int NUMBER_OF_STUDENTS = 5;
int score[NUMBER_OF_STUDENTS];
Improves readability
Improves versatility
Improves maintainability
Slide 13
Uses of Defined Constant
Use everywhere size of array is needed
In for-loop for traversal:
for (idx = 0; idx < NUMBER_OF_STUDENTS; idx++)
{
// Manipulate array
}
In calculations involving size:
lastIndex = (NUMBER_OF_STUDENTS – 1);
When passing array to functions (later)
If size changes requires only ONE
change in program!
Slide 14
Arrays in Memory
Recall simple variables:
Allocated memory in an ‘address’
Array declarations allocate memory for
entire array
Sequentially-allocated
Means addresses allocated ‘back-to-back’
Allows indexing calculations
Simple ‘addition’ from array beginning (index 0)
Slide 15
An Array in Memory
Display 5.2,
page 178
Slide 16
Initializing Arrays
As simple variables can be initialized at
declaration:
int price = 1; // 1 is initial value
Arrays can as well:
int children[3] = {2, 12, 1};
Equivalent to following:
int children[3];
children[0] = 2;
children[1] = 12;
children[2] = 1;
Slide 17
Auto-Initializing Arrays
If fewer values than size supplied:
Fills from beginning
Fills ‘rest’ with zero of array base type
If array-size is left out
Declares array with size required based on
number of initialization values
Example:
int b[] = {5, 12, 11};
Allocates array b to size 3
Slide 18
Initializing Arrays with 0
#include <iostream>
using namespace std;
int main()
{
int x[5]={0};
for(int index=0;index<5;index++)
cout<<x[index]<<endl;
system("pause");
return 0;
}
// Explicitly initializes first element to zero
// Implicitly initializes remaining nine elements to zero
Slide 19
Arrays in Functions
As arguments to functions
Indexed variables
An individual ‘element’ of an array can be
function parameter
Entire arrays
All array elements can be passed as ‘one entity’
Slide 20
Indexed Variables as Arguments
Indexed variable handled same as simple
variable of array base type
Given this function declaration:
void myFunction(double par1);
And these declarations:
int i; double n, a[10];
Can make these function calls:
myFunction(i); // i is converted to double
myFunction(a[3]); // a[3] is double
myFunction(n); // n is double
Slide 21
Entire Arrays as Arguments
Formal parameter can be entire array
Argument then passed in function call
is array name
Called ‘array parameter’
Send size of array as well
Typically done as second parameter
Simple int type formal parameter
Slide 22
Passing Arrays to Functions
To pass an array argument to a function
Specify array name without brackets
Array hours is declared as
int hours[ 24 ];
The function call
modifyArray( hours, 24 );
passes array hours and its size to function modifyArray
23
Passing Arrays to Functions (Cont.)
24
Example
#include <iostream>
using namespace std;
int sumarray(int [], int size);//function prototype
int main()
{
int array[]={2,4,0,8,6};
cout<<sumarray(array,5);//function call
system("pause");
return 0;
}
int sumarray(int a[], int size)//function definition
{ int sum=0;
for(int i=0;i<size;i++)
sum=sum + a[i];
return sum;
}
Example
Write a program that will read 10 char array,
then the program will find how many capital
letters in this array.
Use the following prototype:
void cap_letters(char[], int);
Solution
#include <iostream>
using namespace std;
void cap_letters(char[], int);
int main()
{
char ch[10];
cout<<"enter 10 characters";
for(int i=0;i<10;i++)
cin>>ch[i];
cap_letters(ch,10);
system("pause");
return 0;
}
void cap_letters(char ch[], int size)
{
int count=0;
for(int i=0;i<size;i++)
{
if(ch[i]>='A' &&ch[i]<='Z')
count++;
}
Slide 28
The const Parameter Modifier
Recall: array parameter actually passes
address of 1st element
Similar to pass-by-reference
Function can then modify array!
Often desirable, sometimes not!
Protect array contents from modification
Use ‘const’ modifier before array parameter
Called ‘constant array parameter’
Tells compiler to ‘not allow’ modifications
Slide 29
Global Constants vs. Parameters
Constants typically made ‘global’
Declared above main()
Functions then have scope to array
size constant
No need to send as parameter then?
Technically yes
Why should we anyway?
Function definition might be in separate file
Function might be used by other programs!
Slide 30
Two dimensional Array
or 2-D Array
Multidimensional Arrays
Arrays with more than one index
char page[30][100];
Two indexes: An ‘array of arrays’
Visualize as:
page[0][0], page[0][1], …, page[0][99]
page[1][0], page[1][1], …, page[1][99]
…
page[29][0], page[29][1], …, page[29][99]
C++ allows any number of indexes
Typically no more than two
Slide 32
Multidimensional Array
Multidimensional arrays with two dimensions
Called two dimensional or 2-D arrays
Represent tables of values with rows and columns
33
Multidimensional Array (Cont.)
Declaring and initializing two-dimensional arrays
Declaring two-dimensional array b of 2 rows and 2 columns
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
1 and 2 initialize b[ 0 ][ 0 ] and b[ 0 ][ 1 ]
3 and 4 initialize b[ 1 ][ 0 ] and b[ 1 ][ 1 ]
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Row 0 contains values 1 and 0 (implicitly initialized to zero)
Row 1 contains values 3 and 4
Declaring two dimensional array a of 3 rows and 4 columns
int a[ 3 ][ 4 ] = {0,1,2,3,4,5,6,7,8,9,10,11};
34
Two-dimensional array with three rows and
four columns.
35
Multidimensional Array (Cont.)
Size of first dimension is not required if the array is initialized
but the second dimension should be specified so the Compiler
know how many elements to skip to move to the second element
in the first dimension
char ch[3][3]={{'A','C','F'},
{'D','A','J'},
{'B','E','K'}};
char ch[][3]={{'A','C','F'},
{'D','A','J'},
{'B','E','K'}};
Slide 36
Example
#include <iostream>
using namespace std;
int main ()
{
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
return 0;
}
Multidimensional Array
As explained before, you can have arrays with
any number of dimensions, although it is likely
that most of the arrays you create will be of one
or two dimensions.
Multidimensional Array and Functions
Multidimensional array parameters
Size of first dimension is not required
As with a one-dimensional array
Size of subsequent dimensions are required
Compiler must know how many elements to skip to move to the second element
in the first dimension
Example
void printArray( const int a[][ 3 ] );
Function will skip row 0’s 3 elements to access row 1’s elements
(a[ 1 ][ x ])
39
Case Study: Class GradeBook Using a
Two-Dimensional Array
Class GradeBook
One-dimensional array
Store student grades on a single exam
Two-dimensional array
Store multiple grades for a single student and multiple
students for the class as a whole
Each row represents a student’s grades
Each column represents all the grades the students earned
40
Example
#include <iostream>
int sum_matrix(const int matrix[][3])
using namespace std;
//function definition
int sum_matrix(const int [][3]);
//function prototype
{ int sum=0;
int main()
for(int row=0;row<5;row++)
{
{
int matrix[5][3];
for(int col=0;col<3;col++)
for(int i=0;i<5;i++)
{
sum=sum + matrix[row][col];
for(int j=0;j<3;j++)
}
{
return sum;
cout<< "enter an integer";
}
cin>>matrix[i][j];
}}
cout<<sum_matrix(matrix);
//function call
system("pause");
return 0;
}
Example
Write a program that reads 6X4 2-D array of type
character, then the program will find how many
times the letter (‘A’) appears in this array.
Slide 42
Example
Write a program that reads 5X5 2-D array of type
integer, then the program will find the maximum
of each row in this array and store them in
1-D array.
Summary 1
Array is collection of ‘same type’ data
Indexed variables of array used just like
any other simple variables
for-loop ‘natural’ way to traverse arrays
Programmer responsible for staying
‘in bounds’ of array
Array parameter is ‘new’ kind
Similar to call-by-reference
Slide 44
Summary 2
Array elements stored sequentially
‘Contiguous’ portion of memory
Only address of 1st element is passed to
functions
Constant array parameters
Prevent modification of array contents
Multidimensional arrays
Create ‘array of arrays’
Slide 45