1
Array
Dr. Hadeer A. Hosny
2 Points to be covered:
Introduction to array
Defining array
Storing and accessing array elements
Copying array
Comparing array
Two dimension array (Matrix)
Exercise
3
Introduction to array
An array is used to
store a collection of
data, but it is often
more useful to think of
an array as a
collection of variables
of the same type.
Represented as a
group of consecutive
memory locations
(sequentially stored).
Defining array
4
When defining arrays, specify
Array Name
Type of elements in array
Number of elements (arraySize)
Declaration: type arrayName [ arraySize ];
Examples:
Int c[ 10 ];
float myArray[ 3284 ];
Defining multiple arrays of same type
Format similar to regular variables
Example:
Int b[ 100 ], x[ 27 ];
Defining array
5
Examples
Int A[10]
An array of ten integers
A[0], A[1], …, A[9]
double B[20]
An array of twenty long floating point numbers
B[0], B[1], …, B[19]
Array indexes always start at zero in C++
Defining array
6 Array Initializer
int n[ 5 ] = { 1, 2, 3, 4, 5 };
If not enough elements to store in array , the remaining
elements will be zero
int n[ 5 ] = { 0 }
All elements stored in array will be 0
int n[ 5 ] = { 5,6,7,8,9,0,9 }
Here too many elements want to be stored in array , so a
syntax error occurs
int n[ ] = { 1, 2, 3, 4, 5 }; Index
5 elements are stored, therefore size or array is 5
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
Element
Storing array elements
7
Three ways to enter elements (values) in array:
1.Initialize arrays in the variable declaration statement
Example: double temperature [5]= {12.3,7.5,65,72.1,87.5};
2.Read input values into the array from the keyboard or
from a file and then store them in array using loop.
Example
Array elements are commonly used in loops
int size=10; int a[size],index;
for(index =0; index<=size-1; index++) { cin>>a[index]; }
To access all elements of an array a for loop is used, for loop will start
from index 0 to the last element in the array which has an index of array
size-1
When looping through an array, the array index should never go below
0 and always be less than the total number of elements in the array
(size –1).
Storing array elements
8
Three ways to enter elements (values) in array:
3.Use assignment statements.
Example: declaration: int score [6];
score[0]=49;
score[1]=75;
score[2] = 65;
score[3] = 90;
score[4]=77;
score[5]=70;
Accessing array elements
9
To refer to an element, specify
Array name
Position number
Format:
Arrayname [position number]
First element at position (index) 0
n element array named c:
c[ 0 ], c[ 1 ]...c[ n –1 ]
Array elements are like normal variables
c[ 0 ] = 3;
cout<< c[ 0 ];
Perform operations in 4th index. (x=3)
c[ 5 -2 ] == c[ 3 ] == c[ x ]
Note: We cannot use assignment statements with entire arrays.
Accessing array elements
10
We cannot use assignment statements with entire arrays.
All of the following are valid:
score[0] = 4;
score[0] += 7;
score[1] = score[0] -2;
score[2] = score[1] + 5 * score[0];
score[j] = score[j + 1];
Note: index can be any integral expression.
11
Example on dealing with array.
#include <iostream >
using namespace std;
for loop initializes
each array element
/* function main begins program execution */ separately
int main( void )
{
/* symbolic constant SIZE can be used to specify array
size */
int s[ 10 ]; /* array s has SIZE elements */
int j; /* counter */
for ( j = 0; j < 10; j++ ) { /* set the values */
s[ j ] = 2 + 2 * j;
} /* end for */
cout <<"Element Value\n" ;
/* output contents of array s in tabular format */
for ( j = 0; j < 10; j++ ) {
cout<<"\t"<< j<<"\t" <<s[ j ]<<"\n" ;} /* end for */
return 0; /* indicates successful termination */
for loop print index and
} /* end main */ each array element
separately
Copying arrays
12
This is not the way to copy an array.
int array1[] = { 2, 4, 6, 8, 10 };
int array2[] = array1; // This does not copy array1.
Copying arrays
13
Solution is to copy element by element in array.
int array1[ ] = {2, 4, 6, 8, 10 };
int array2[5];
for (int i= 0; i< 5; i++){
array2[i] = array1[i];
}
Comparing arrays
14
Variables
Int x,y;
if (x==y) {cout<<“x equals y”;}
Arrays
int firstArray[ ] = { 5, 10, 15, 20, 25 };
int secondArray[ ] = { 5, 10, 15, 20, 25 };
if (firstArray==secondArray)
cout<<"The arrays are the same.";
No
Why?
15
Example on comparing array.
#include<iostream>
using namespace std;
int main(){ Compare 2 arrays
int firstArray[] = { 2, 4, 6, 8, 10 };
content
int secondArray[] = { 2, 4, 6, 8, 10 };
bool arraysEqual = true;
int size2=5, size1=5, i=0;
// First determine whether the arrays are same size.
if (size1 != size2)
arraysEqual= false;
// Next determine whether the elements contain same data.
while ( arraysEqual ==true && i< 5)
{
if (firstArray [i] != secondArray[i]){
arraysEqual= false; }
i++;
}
if (arraysEqual==true)
cout <<"The arrays are equal .";
else
cout <<"The arrays are not equal .";
return 0;
}
Two dimension array
16
A two-dimensional array is an array of arrays.
Table, with rows and columns .
index
Two dimension array
17
Initializing Two-Dimensional Arrays
Multi dimensioned arrays may be initialized by
specifying bracketed values for each row. Following is
an array with 3 rows and each row have 4 columns.
Example:
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are
optional. The following initialization is equivalent to
previous example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Two dimension array
18
Initializing Arrays
Programs that process two-dimensional arrays can do so
with nested loops.
To fill the scores array:
int scores[3][4];
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 4; col++)
{
cout<<"Enter a score: ";
cin>>scores[row][col];
}
}
Two dimension array
19
To print the scores array:
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 4; col++)
{
cout<<scores[row][col];
}
}
20
Example multi dimension array.
#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}};
// output each array element's value
for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 2; j++ ) {
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
21
Exercise
Write a program that reads the scores of 20 students, and
print:
The Maximum value of elements stored in an array.
The Average value of elements stored in an array.
The Minimum value of elements stored in an array.
22
Outline of course
Contents going to be covered during the course:
Problem Solving
Flow chart, pseudo code, and Algorithm
Starting writing first C++ program
Input and Output
Conditions
Loops
Array
Function
Pointers
String
OOP
23