0% found this document useful (0 votes)
68 views

Arrays: Dr. Hadeer Ahmed Hassan Hosny

The document discusses arrays in C++. It begins by introducing arrays and how they store a collection of data of the same type in consecutive memory locations. It then covers defining and initializing arrays, storing values in arrays, accessing array elements using indexes, copying the contents of one array to another, comparing arrays for equality, passing arrays to functions, and returning arrays from functions. The document provides examples for many of these array concepts.

Uploaded by

koumton
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

Arrays: Dr. Hadeer Ahmed Hassan Hosny

The document discusses arrays in C++. It begins by introducing arrays and how they store a collection of data of the same type in consecutive memory locations. It then covers defining and initializing arrays, storing values in arrays, accessing array elements using indexes, copying the contents of one array to another, comparing arrays for equality, passing arrays to functions, and returning arrays from functions. The document provides examples for many of these array concepts.

Uploaded by

koumton
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

1

Arrays

Dr. Hadeer Ahmed Hassan Hosny

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

 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, 17.0, 50.0};
 Or double balance[5] = {1000.0, 2.0, 3.4, 17.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 ]
Accessing array elements
10

 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.
#define directive tells compiler to
replace all instances of the word
SIZE with 10
#include <iostream >
using namespace std;
for loop initializes
#define SIZE 10 /* maximum size of array */ each array element
/* function main begins program execution */ separately
int main( void )
{
/* symbolic constant SIZE can be used to specify array
size */
int s[ SIZE ]; /* array s has SIZE elements */
int j; /* counter */
for ( j = 0; j < SIZE; 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 < SIZE; 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;
}
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)

 You can return a pointer to an array by specifying the array's


name without an index.
 int * reverse(const int list[], 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];

for (int i = 0; i < 10; ++i) { Returning array as a


r[i] = i+1;
pointer
cout << r[i] << "\n";
}
return r;
}
// main function to call above defined function.
int main () {
// a pointer to an int.
int *p;
p = getNumber();
for ( int i = 0; i < 10; i++ ) {
cout << *(p) << endl;
p++;
}
return 0;
}
Two dimension array
21
 A two-dimensional array is an array of arrays.
 Table, with rows and columns .
index

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:

for (int row = 0; row < 3; row++)


{
for (int col = 0; col < 4; col++)
{
cout<<scores[row][col];
}
}
25
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;
}
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.

You might also like