0% found this document useful (0 votes)
15 views48 pages

Chapter 7

Uploaded by

maryam osama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views48 pages

Chapter 7

Uploaded by

maryam osama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Introduction to Computer Programming (CSCI 112)

Chapter 7
Arrays

Dr. Ali Alnoman


Spring 2023

Reference: C++ How to Program, 10th edition, P. Deitel and H. Deitel


2

Objectives
• Use arrays to store, sort and search lists and tables of values
• Declare arrays, initialize arrays, and refer to the individual elements of arrays
• Pass arrays to functions
• Basic searching and sorting techniques
• Declare and manipulate multidimensional arrays
3

Arrays
• An array is a contiguous group of memory locations that have the same data type
• To refer to a particular location or element in the array: specify the name of the array
and the position number of the particular element
• The following figure shows an integer array called c
▫ The array c has 12 elements
▫ The position number is called a subscript or index (this number specifies the number of elements
from the beginning of the array)
▫ The first element in every array has subscript 0 (zero) and is sometimes called the zeroth element
[zero-based addressing]
▫ The highest subscript in array c is 11, which is 1 less than the number of elements in the array (12)
▫ A subscript must be an integer
4
5
6

Arrays
• As mentioned earlier, each element in an array can be called by giving the array
name followed by the element position in square brackets [ ] (also referred to as a
subscript)
• The first position is numbered 0
• For example, the elements in an array A that has three elements that can be
addressed by:
A[0] A[1] A[2]
7

Declaring arrays
• Arrays occupy space in memory
• To specify the type of the elements and the number of elements required by an array
use a declaration of the form:
arraytype arrayName; Example: int arr;

• The compiler reserves the appropriate amount of memory based on the type of the
elements and the arraySize
• Arrays can be declared to contain values of most data types
8

Declaring and Initializing Arrays


• To reserve 10 elements in an integer array C, we write:
int C[10];

• Elements in the array C above are arranged from 0 to 9, the first element is C[0]
and the last is C[9]
• We can initialize the values of elements using the FOR loop:

for (int i = 0; i < 10; ++i ) {


C[i] = 0; // assign 0 to the element at location i
}
9

Declaring and Initializing Arrays


• To initialize an array using the initializing list:

int n[8] = { 32, 27, 64, 18, 95, 14, 90, 70};

• To initialize the entire array with zeros:


int n[8] = {0};

• If the number of elements is unknown, we can omit the array size in the array
definition, it will be calculated automatically:
int n[] = {1, 2, 3, 4, 5};

double grades[]= {90.5, 65.1, 87.0, 72.9};


10

Examples Using arrays


• The following examples demonstrate:

▫ how to declare arrays

▫ how to initialize arrays

▫ how to perform common array manipulation


11

Declaring an initialize an array

Exercise: Declare an array n with 5 elements and initialize all elements with 0
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n[ 5 ]; // n is an array of 10 integers

// initialize elements of array n to 0


for ( int i = 0; i < 5; ++i )
n[ i ] = 0; // set element at location i to 0

cout << "Element" << setw( 13 ) << "Value" << endl;

// output each array element's value


for ( int j = 0; j < 5; ++j )
cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;
} // end main
12

OUTPUT
13

Initializing an array with an initializer list


• The following program uses an initializer list to initialize an integer array of five
values and displays the array in tabular format
• If there are fewer initializers than the number of array elements, the remaining array
elements are initialized to zero
14

Exercise:
Declare an array n with 5 elements 32, 27, 64, 18, 95

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
// use initializer list to initialize array n
int n[ 5 ] = { 32, 27, 64, 18, 95 };

cout << "Element" << setw( 13 ) << "Value" << endl;

// output each array element's value


for ( int i = 0; i < 5; ++i )
cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;

} // end main
15

OUTPUT
16

Using Array Elements in Calculations


• The following program sets the elements of a 10-element array s to the even integers
2, 4, 6, 8, 10, 12, 14, 16, 18, 20 and prints the array in tabular format
• The code uses a const qualifier to declare a constant variable arraySize with the
value 10
• A constant variable that’s used to specify array’s size must be initialized with a
constant expression when it’s declared and cannot be modified thereafter
• Constant variables are also called named constants or read-only variables
17

Exercise:
Declare an array s with 10 elements. These elements are even integers from 2-20
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// constant variable can be used to specify array size
const int arraySize = 10;
int s[ arraySize ]; // array s has 10 elements
for ( int i = 0; i < arraySize; ++i ) // set the values
s[ i ] = 2 + 2 * i;
cout << "Element" << setw( 13 ) << "Value" << endl;

// output contents of array s in tabular format


for ( int j = 0; j < arraySize; ++j )
cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl;
} // end main
18

OUTPUT
19

Exercise: Adding the Elements of an array


#include <iostream>
using namespace std;

int main()
{
const int arraySize = 10; // constant variable indicating size of array
int a[ arraySize ] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
int total = 0;

// sum contents of array a


for ( int i = 0; i < arraySize; ++i )
total += a[ i ];
OUTPUT
cout << "Total of array elements: " << total << endl;
} // end main
20

Using Bar Charts to Display array Data Graphically


• Many programs present data to users in a graphical manner
• One simple way to display numeric data graphically is with a bar chart that shows
each numeric value as a bar of asterisks (*)
• Our next program stores data in an array of 11 elements, then prints the bar chart
for these numbers
• The program uses the array n = {2, 7, 5, 4, 0, 9, 1, 2, 4, 2, 1}
21

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
const int arraySize = 11;
OUTPUT
int n[ arraySize ] = {2, 7, 1, 4, 0, 9, 1, 2, 4, 2, 1}; Bar Chart of Array Elements
cout << “Bar Chart of Array Elements" << endl; 2 **
// for each element of array n, output a bar of the chart 7 *******
1 *
for ( int i = 0; i < arraySize; ++i ) 4 ****
{ 0
cout << n[i] << " "; 9 *********
1 *
// print bar of asterisks
2 **
for ( int stars = 0; stars < n[ i ]; ++stars ) 4 ****
cout << '*'; 2 **
1 *
cout << endl; // start a new line of output
} // end outer for

} // end main
22

Using the Elements of an array as Counters


• In a previous topic, we used separate counters in our die-rolling program to track the
number of occurrences of each side of a die as the program rolled the die 6,000,000
times

• An array version of this program is shown next


23

// Roll a six-sided die 6,000,000 times.


#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime> OUTPUT
using namespace std;
int main()
{
int arraySize = 7; // ignore element zero
int frequency[ arraySize ] = {}; // initialize elements to 0

srand( time( 0 ) ); // seed random number generator

// roll die 6,000,000 times; use die value as frequency index


for ( int roll = 1; roll <= 6000000; ++roll )
++frequency[ 1 + rand() % 6 ];

cout << "Face" << setw( 13 ) << "Frequency" << endl;

// output each array element's value


for ( int face = 1; face < arraySize; ++face )
cout << setw( 4 ) << face << setw( 13 ) << frequency[ face ] << endl;
} // end main
24

Using arrays to Summarize Survey Results


• Our next example uses arrays to summarize the results of data collected
in a survey
• Consider the following problem statement:
Twenty students were asked to rate on a scale of 1 to 5 the quality of the
food in the student cafeteria, with 1 being “awful” and 5 being “excellent.”
Place the 20 responses in an integer array and determine the frequency of
each rating
25

#include <iostream> for (int answer = 0; answer < responseSize;++answer)


#include <iomanip> ++frequency[ responses[ answer ] ];
using namespace std;
Cout << "Rating" << setw( 17 ) << "Frequency" <<
int main() endl;
{
// define array sizes // output each array element's value
int responseSize = 20; for ( int rating = 1; rating < frequencySize;
// size of array responses ++rating )
int frequencySize = 6; cout << setw( 6 ) << rating << setw( 17 ) <<
// size of array frequency frequency[ rating ] << endl;
} // end main

// place survey responses in array responses


int responses[ responseSize ] = { 1, 2, 5, 4, 3, 5,
2, 1, 3, 1, 4, 3, 3, 3, 2, 3, 3, 2, 2, 5 };
OUTPUT
// initialize frequency counters to 0
int frequency[ frequencySize ] = {};
//for each answer, select responses element and use
that value as frequency subscript to determine
element to increment
26

Using arrays to Summarize Survey Results


• It’s important to ensure that every subscript you use to access an array element is
within the array’s bounds - that is, greater than or equal to 0 and less than the
number of array elements

• Reading from out-of-bounds array elements can cause a program to crash or even
appear to execute correctly while using bad data

• Writing to an out-of-bounds element (known as a buffer overflow) can corrupt a


program’s data in memory, crash a program and allow attackers to exploit the system
and execute their own code
27

Passing an Array to a Function


First, let’s define (declare) an array:
int array_name[ array_size ];

• Now, pass the array to a function (function_name):


function_name(array_name, array_size)

• Dealing with an array element is not different from any


other singular variable
Note:
Arrays are invoked without brackets: array_name not array_name[]
28

Passing an Array to a Function: Example


#include <iostream>
#include <iomanip> // output modified array elements
using namespace std; for ( int j = 0; j < arraySize; ++j )
void modifyArray( int [], int ); // receive array cout << setw( 3 ) << a[ j ];

int main() } // end main


{
int arraySize = 5; // size of array a
int a[ arraySize ] = { 0, 1, 2, 3, 4 };

// output original array elements


for ( int i = 0; i < arraySize; ++i ) void modifyArray( int b[], int sizeOfArray )
cout << setw( 3 ) << a[ i ]; {
// multiply each array element by 2
cout << endl; for ( int k = 0; k < sizeOfArray; ++k )
b[ k ] *= 2;
} // end function modifyArray
modifyArray( a, arraySize );
cout << "The values of the modified array
are:\n";
29

OUTPUT
30

Passing an Array Element to a Function: Example


#include <iostream> modifyElement( a[ 3 ] );
#include <iomanip> // pass array element a[ 3 ]
using namespace std;
cout << " a[3] after modifyElement: " << a[ 3 ] <<
void modifyElement( int ); // receive array element endl;
} // end main
int main()
{
int arraySize = 5; // size of array a
int a[ arraySize ] = { 0, 1, 2, 3, 4 };
void modifyElement( int e )
// output original array elements {
for ( int i = 0; i < arraySize; ++i ) // multiply parameter by 2
cout << setw( 3 ) << a[ i ]; cout << " Value of element in modifyElement: "
<< ( e *= 2 ) << endl;
cout << endl; } // end function modifyElement
31

OUTPUT
32

Static Local arrays and Automatic Local arrays


• We can apply static to a local array declaration so that it will not be created and
initialized each time the program calls the function and is not destroyed each time
the function terminates. This can improve performance, especially when using large
arrays
33

Static Local arrays and Automatic Local arrays


#include <iostream>
using namespace std;

void staticArrayInit( void ); // function prototype


void automaticArrayInit( void ); // function prototype
const int arraySize = 3;

int main()
{
cout << "First call to each function:\n";
staticArrayInit();
automaticArrayInit();

cout << "\n\nSecond call to each function:\n";


staticArrayInit();
automaticArrayInit();
cout << endl;
} // end main

The code continues in the next slide…


34

// function to demonstrate a static local array


void staticArrayInit( void )
{
// initializes elements to 0 first time function is called
static int array1[ arraySize ]; // static local array
cout << "\nValues on entering staticArrayInit:\n";

// output contents of array1


for ( int i = 0; i < arraySize; ++i )
cout << "array1[" << i << "] = " << array1[ i ] << " ";

cout << "\nValues on exiting staticArrayInit:\n";

// modify and output contents of array1


for ( int j = 0; j < arraySize; ++j )
cout << "array1[" << j << "] = " << ( array1[ j ] += 5 ) << " ";
} // end function staticArrayInit
35

// function to demonstrate an automatic local array


void automaticArrayInit( void )
{
// initializes elements each time function is called
int array2[ arraySize ] = { 1, 2, 3 }; // automatic local array
cout << "\n\nValues on entering automaticArrayInit:\n";

// output contents of array2


for ( int i = 0; i < arraySize; ++i )
cout << "array2[" << i << "] = " << array2[ i ] << " ";

cout << "\nValues on exiting automaticArrayInit:\n";

// modify and output contents of array2


for ( int j = 0; j < arraySize; ++j )
cout << "array2[" << j << "] = " << ( array2[ j ] += 5 ) << " ";
} // end function automaticArrayInit
36

OUTPUT
37

Searching Arrays with Linear Search


• Often it may be necessary to determine whether an array contains a value that
matches a certain key value
• The process of finding a particular element of an array is called searching
• The linear search compares each element of an array with a search key
• To determine that a value is not in the array, the program must compare the search
key to every element of the array
• The following is a program that performs linear search
38

#include <iostream>
using namespace std; // display results
if ( element != -1 )
int linearSearch(int [], int, int ); cout << "Found value in element " << element
// prototype << endl;
else
int main() cout << "Value not found" << endl;
{ } // end main
int arraySize = 100; // size of array a
int a[ arraySize ]; // create array a // compare key to every element of array until
int searchKey; // value to locate in array a // location is found or until end of array is
// reached; return subscript of element if key is
for ( int i = 0; i < arraySize; ++i ) // found or -1 if key not found
a[ i ] = 2 * i; // create some data int linearSearch(int array[], int key, int
sizeOfArray )
cout << "Enter integer search key: "; {
cin >> searchKey; for ( int j = 0; j < sizeOfArray; ++j )
if ( array[ j ] == key ) // if found
// attempt to locate searchKey in array a return j; // return location of key
int element = linearSearch( a, searchKey,
arraySize ); return -1; // key not found
} // end function linearSearch
39

Sorting an array
• Sorting data (i.e., placing the data into some particular order such as ascending or
descending) is one of the important computing applications
• A bank sorts all checks by account number so that it can prepare individual bank
statements at the end of each month
• Telephone companies sort their phone directories by last name and, within that by
first name, to make it easy to find phone numbers
40

Bubble Sort
• Bubble sort compares successive pairs of elements, swapping whenever the bottom
element of the pair is smaller than the one above it. In this way the smallest element
“bubbles up” to the top of the list
• The following program performs bubble sort

https://i.stack.imgur.com/XNbE0.gif
41

#include <iostream> // element is greater than second element


#include <iomanip> if ( a[ i ] > a[ i + 1 ] )
using namespace std; {
hold = a[ i ];
int main() a[ i ] = a[ i + 1 ];
{ a[ i + 1 ] = hold;
} // end if
int size=10;
int a[size]={5,3,1,8,6,2,9,0,2,8}; } // end inner for
int hold; } // end outer for

for (int j=0;j<size;++j) for (int j=0;j<size;++j)


cout << a[j] << " "; cout << a[j] << " ";

cout << endl;

for (int k = 0; k < size-1; ++k ) { } // end main


for ( int i = 0; i < size-1; ++i ) { OUTPUT
// compare adjacent elements and swap them if
first
42

Multidimensional Arrays
• You can use arrays with two dimensions (i.e., 2D subscripts) to represent
tables of values consisting of information arranged in rows and columns
• To identify a particular table element, we must specify two subscripts
[row,column] by convention, the first identifies the element’s row and the
second identifies the element’s column
• Arrays with two or more dimensions are known as multidimensional arrays
43

The figure below illustrates a two-dimensional array named “a”


• The array contains three rows and four columns, so it’s said to be a 3-by-4 array
• In general, an array with m rows and n columns is called an m-by-n array
44

Multidimensional Arrays

• A 2-by-2 array can be initialized as follows:


int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
45

Multidimensional arrays: Nested "FOR" Loops


• Nested Range-Based for Statements
• To process the elements of a two-dimensional array, we use a nested loop in which
the outer loop iterates through the rows and the inner loop iterates through the
columns of a given row
• To set all elements in row 2 of a 4-by-4 array to zero:
for ( int column = 0; column < 4; ++column )
a[ 2 ][ column ] = 0;

This is equivalent to:


46

Exercise 1: What is the output?


#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
int matrix[3][4] = { {1,2,3,4},{5,6,7,8},{9,10,11,12} };

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


{
for (int j=0; j<4; j++) OUTPUT
cout << setw(4) << matrix[i][j];

cout << endl;


}
}
47

Exercise 2: Sum of all elements in a 2D array


#include <iostream>
using namespace std;

int main()
{
int a[3][4] = { {1,2,3,4},{5,6,7,8},{9,10,11,12} };
int total = 0;
for ( int row = 0; row < 3; ++row )
for ( int column = 0; column < 4; ++column )
total += a[ row ][ column ];

cout << “Sum of array elements is " << total << endl;
}

OUTPUT
Sum of array elements is 78
48

Exercise 3: What is the error?


double f[ 3 ] = { 1.1, 10.01, 100.001, 1000.0001 };
Error: f[3] should be f[4]

double d[ 2 ][ 10 ];
d[ 1, 9 ] = 2.345;
Error: d[1,9] has to be d[1][9]

int a[ 3 ]={5,10,15};
cout << a[ 1 ] << " " << a[ 2 ] << " " << a[ 3 ] << endl;
Error: we should write cout << a[ 0 ] << " " << a[ 1] << " " << a[ 2] << endl;

You might also like