Arrays: Dr. Hadeer Ahmed Hassan Hosny
Arrays: Dr. Hadeer Ahmed Hassan Hosny
Arrays
Second term
2021
2 Points to be covered:
Introduction to array
Defining array
Storing and accessing array elements
Copying array
Comparing array
Array dealing with function
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
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]
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]
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;
}
Passing arrays to functions
16 Normally when you pass an array to a function, you should
also pass its size in another argument. Otherwise, you will have
to hard code this in to the function or declare it in a global
variable.
Example:
void func(int list[], int size)
Passing an array variable means that the starting address of the
array is passed to the formal parameter by value. The
parameter inside the function references to the same array that
is passed to the function. No new arrays are created.
You can pass a pointer to an array by specifying the array's
name without an index.
Example:
void func(int *list, int size)
Passing arrays to functions
17
Passing arrays by reference makes sense for performance
reasons. Passing arrays by its reference value could lead to
errors if your function changes the array accidentally. To
prevent it from happening, you can put the const keyword
before the array parameter to tell the compiler that the array
cannot be changed. The compiler will report errors if the code
in the function attempts to modify the array.
Example:
void func(const int list[], int size)
Example on passing array to function.
18
#include <iostream>
using namespace std;
// function declaration:
double getAverage(int arr[], int size); Passing array to
function
int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg <<"\n";
return 0;
}
double getAverage(int arr[], int size) {
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = double(sum) / size;
return avg;
}
Returning array from functions
19 C++ does not allow to return an entire array as an argument to
a function. However, you can return a pointer to an array by
specifying the array's name without an index or pass another
array to store result in it.
// Return the reversal of list Not allowed in c++
int[] reverse(const int list[], int size)
However, you can circumvent this restriction by passing two
array arguments in the function, as follows:
// newList is the reversal of list
Void reverse(const int list[], int newList[], int size)
Remember that C++ does not advocate to return the address of a local
variable to outside of the function so you would have to define the
local variable as static variable.
Example on returning array from a
20 function.
#include <iostream>
#include <ctime>
using namespace std; Using static
// function to generate and return random numbers.
int * getNumber( ) {
static int r[10];
4
Two dimension array
22
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
23
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
24
To print the scores 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}};
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
Two dimension array
26
Passing Two-Dimensional Arrays to Functions
You can pass a two dimensional array to a function;
however, C++ requires that the column size to be specified
in the function declaration.
Example:
void func(int list[][3],int size)
C++ does not limit the number of dimensions that an array
may be.
More than three dimensions is hard to visualize, but can be
useful in some programming problems.
IntX[3][3][4];
27
Exercise
Write the following functions:
Write a function named Maximum that receives an array
as input parameter, and returns the maximum value.
Write a function named Average that receives an array
as input parameter, and returns the average value.
Write a function named Count that receives an array as
input parameter, and returns the number of array values
above or equal 50.
Then, write a program that uses the above functions to
read the scores of 20 students, and print:
Average score.
Maximum score.
Number of succeeded students.