Arrays

1 / 56

# Arrays - PowerPoint PPT Presentation

Arrays. One Dimensional Arrays. A data structure used for storage of a collection of data items that are all the same type. Individual data items are stored in adjacent cells of main memory. . Declaring Arrays.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about 'Arrays' - ave

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

### Arrays

One Dimensional Arrays
• A data structure used for storage of a collection of data items that are all the same type.
• Individual data items are stored in adjacent cells of main memory.
Declaring Arrays
• Assign one variable name to a collection of two or more adjacent memory cells. Must declare: typearray-name [size];
Declaring Arrays
• Examples:double temperature [5];
double temperature [5];

12.3

temperature [0]

7.5

temperature [1]

65.0

temperature [2]

72.1

temperature [3]

87.5

temperature [4]

double temperature [5];

12.3

temperature [0]

7.5

temperature [1]

65.0

temperature [2]

Elements

72.1

temperature [3]

87.5

temperature [4]

double temperature [5];

12.3

temperature [0]

7.5

temperature [1]

65.0

temperature [2]

SubscriptorIndex

72.1

temperature [3]

87.5

temperature [4]

Printing the Array

cout<<temperature [0];cout<<temperature [1];cout<<temperature [2];cout<<temperature [3];cout<<temperature [4];

Printing the Array

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

{

cout<<temperature[i]<<endl;

}

Subscript Variable

Assignment Statement

temperature [4] = 12.7;orN = 4;temperature [N] = 12.7;

Three ways to get values into array elements

• Use assignment statements
• Initialize arrays in the variable declaration statement
• Read input values into the array from the keyboard or from a file

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

{

cout<<“enter temperature “<<i<< “ “;

cin>>temperature[i];

}

cin>>temperature[0]>>temperature[1]>> temperature[2]>>temperature[3]>> temperature[4];

Average Temperature

double sum = 0.0;

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

{

sum += temperature[i];

}

average = sum / 5.0;

• We may use constants for the size in an array declaration:const int SIZE = 6;int score[SIZE];

declaration:

int score [6];

score:

49 75 65 90 77 70

index: 0 1 2 3 4 5

(Subscript)

score[2] = 65;

score[0] = 49;

Accessing the Individual Elements of an Array
• If a variable represents an array, we refer to the whole array when we use just the name of the variable ex. score
Accessing Individual Elements
• We access a particular array element by using the array name followed by the index in square brackets: sumTwo = score[3] + score[0];
1. Assigning Values
• We cannot use assignment statements with entire arrays (some languages allow this, but most, including C++, do not handle it)
• Instead, we must assign values to individual elements
• We can use them as values in assignment statements: score[0] = 30; grade[3] = ‘A’; price[2] = 10.39;
Using Array Elements
• 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.
2. Declaration-Initialization
• We can put initial values into an array at declaration time
• We must list all of the values: they must all be constants:int num[5] = {58, 43, 60, 21, 38};
• We don’t have to specify the dimension of the array when we initialize it:int x[ ] = {4, 8, 30, 21, 56, 87};will be an array of six elements
• Exception: you may initialize all elements of an array to 0 with int score_ary[10] = {0};

Lec

p. 132

Array Practice
• Declare an array to hold the tax for up to 10 different sales.
• Declare an array to hold the final letter grades for a class with up to 40 students
• Declare an array of integers which holds the final average for those 40 students and initialize its values to 0
• Declare an array of characters called letter_ary with initial values ‘a’, ‘d’, ‘y’, and ‘w’. What is the value of letter_ary[1]?

3. Enter from keyboard or file

• A for loop is an ideal way to read data into an array. This loop assumes we’re reading exactly 5 elements.

for (i = 0; i < 5; i++)

{

cout << “Please enter a score: ”;

cin >> score[i];

}

Lec

p. 133

More Array Practice
• Write a loop to initialize all 50 elements of array salary_ary to 100.
• Write C++ code to read values from the keyboard to fill the array scores. Input should stop when a negative number is entered. The maximum size of the array is in a constant ARR_SIZE.
• Write C++ code to add up the first num_elements values in the array my_vals and store the sum in the variable my_sum.
More Array Practice
• Assume that your third array already has values. Now write a function to put the appropriate letter grades into the second function.
Error!

#include <iostream>

using namespace std;

int main()

{

int x[10] = {0, 1,2,3,4,5,6,7,8,9};

int n;

cin >> n;

int y[n]; //Line 10 - Here we have (illegally) declared

//an array of non-constant size

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

cout << (y[i] = x[i]) << " " ;

cout<< endl;

return 0;

}

Must be a constant

Display 9.1 Program using an Array

//Reads in 5 scores and shows how much each

//score differs from the highest score.

#include <iostream>

using namespace std;

int main( )

{ int i, score[5], max;

cout << "Enter 5 scores:\n";

cin >> score[0];

max = score[0];

for (i = 1; i < 5; i++)

{ cin >> score[i];

if (score[i] > max)

max = score[i];

//max is the largest of the values score[0],..., score[i].

}

cout << "The highest score is " << max << endl

<< "The scores and their\n"

<< "differences from the highest are:\n";

for (i = 0; i < 5; i++)

cout << score[i] << " off by "

<< (max - score[i]) << endl;

return 0;

}

Dice Example
• Write a C++ program to find the frequency distribution of all possible sums of the roll of two dice.
What Do We Do with Arrays?
• The most common tasks we perform with arrays are to:
• Load information into an array for later processing
• Process each element of an array
• Find a particular element in an array
• Write out the contents of an array
Importance of Loops
• Since we usually want to do something with all of the elements of an array, one at a time, we use loops constantly in array processing
• Sometimes pre-testing loops are appropriate
• Most often, we use counting loops that start with the first index and end with the last index
Using Arrays with Functions
• We can pass individual array elements to functions either by value or by reference
• treat array element same as other variables in the call
• prototype:

void modifyElement(int num);

• call:

modifyElement(arr[3]);

void modifyElement(int num)

{

Arrays and Functions, cont.
• It’s often useful to have a function which passes an entire array as a parameter
• Prototype:void ReadScores(int score[], int NumPlayers);

Arrays and Functions, cont.
• Once inside the function: we handle the elements just as we would elsewhere:ReadScores(int score[], int NumPlayers) { int i; for (i = 0; i < NumPlayers; i++)

{ cin >> score[i]); }}

Note!
• We cannotreturn arrays
• However, if we pass an array to a function, we can modify its contents. So arrays are as if passed by reference.
• To keep the elements of an array from being accidentally modified in a function use the const keyword in the prototype and header:
• void PrintScores(const int score[],int numPlayers);
Parallel Arrays
• Sometimes we have more than one piece of information to go in our array.
• For example, we might want an array of students
• Each one should have an ID number, an average, and a letter grade
• We would use three arrays
• an ID array
• an average array
• and a letter grade array
• The items found at a given index would all relate to the same student
Parallel Arrays

ID_arr:

222 123 445 346 771 708

index: 0 1 2 3 4 5

87.5 75.2 94.0 90.0 77.9 83.9

avg_arr:

index: 0 1 2 3 4 5

B C A A C B

index: 0 1 2 3 4 5

Arrays of Structures

struct StudentInfo

{

int stu_id;

double avg;

}

to declare:

StudentInfo Our_class[40];

to use members:

Our_class[1].stu_id = 123;

More Array Practice
• Write a loop to initialize all 50 elements of array salary_ary to 100.
• Suppose array elements chairs_ary[0] through chairs_ary[49] hold the number of chairs in Room 101 through 150, respectively. Write a loop to print the room number and number of chairs for each room.
More Practice
• Given an array containing the basketball scores for the 26 games played by the Redbirds this season, write a function to find and return the highest score to the calling function. Also write the function prototype and function call.
Array and File Practice
• Assume you have a file containing information about a store’s inventory. Each line of the file has a part number, a price, and a number on hand. Write a function to read data from this file into three parallel arrays. Remember that we don’t know ahead of time how many parts there are, but we will need to know later in the program.
PROGRAMMING EXAMPLE: Searching an Array
• The tasks of searching a data structure and sorting (rearranging data in a data structure to obey some order relation) and analysis to determine the time and space these tasks require as a function of the size of the data structure covers much of Computer Science.
• We illustrate the search task using the sequential search algorithm on an array in Display 9.11.
• This algorithm examines each element of the array in turn until the element is found, or there are no more array elements to examine.
Shows the difference between each of a list of golf scores and their average.

#include <iostream>

using namespace std;

const int MAX_NUMBER_SCORES = 10;

void fill_array(int a[ ], int size, int& number_used);

double compute_average(const int a[ ], int number_used);

void show_difference(const int a[ ], int number_used);

int main( )

{ int score[MAX_NUMBER_SCORES], number_used;

cout << "This program reads golf scores and shows\n"

<< "how much each differs from the average.\n";

cout << "Enter golf scores:\n";

fill_array(score, MAX_NUMBER_SCORES, number_used);

show_difference(score, number_used);

return 0;

}

void fill_array(int a[ ], int size, int& number_used)

{ cout << "Enter up to " << size << " nonnegative whole numbers.\n"

<< "Mark the end of the list with a negative number.\n";

int next, index = 0;

cin >> next;

while ((next >= 0) && (index < size))

{ a[index] = next;

index++;

cin >> next;

}

number_used = index;

}

double compute_average(const int a[], int number_used)

{ double total = 0;

for (int index = 0; index < number_used; index++)

total = total + a[index];

if (number_used > 0)

{ return (total/number_used);

}

else

{ cout << "ERROR: number of elements is 0 in compute_average.\n"

<< "compute_average returns 0.\n";

return 0;

}

}

void show_difference(const int a[ ], int number_used)

{ double average =

compute_average(a,number_used);

cout << "Average of the " << number_used

<< " scores = " << average << endl

<< "The scores are:\n";

for (int index = 0; index < number_used; index++)

cout << a[index] << " differs from average by "

<< (a[index] - average) << endl;

}

Searches a partially filled array of nonnegative integers.

const int DECLARED_SIZE = 20;

void fill_array(int a[ ], int size, int& number_used);

int search(const int a[ ], int number_used, int target);

int main( )

{ int arr[DECLARED_SIZE], list_size, target;

fill_array(arr, DECLARED_SIZE, list_size);

char ans;

int result;

do

{ cout << "Enter a number to search for: ";

cin >> target;

result = search(arr, list_size, target);

if (result == -1)

cout << target << " is not on the list.\n";

else

cout << target << " is stored in array position "

<< result << endl

<< "(Remember: The first position is 0.)\n";

cout << "Search again?(y/n followed by return): ";

cin >> ans;

}while ((ans != \'n\') && (ans != \'N\'));

cout << "End of program.\n";

return 0;

}

void fill_array(int a[ ], int size, int& number_used)

{ cout << "Enter up to " << size << " nonnegative whole numbers.\n"

<< "Mark the end of the list with a negative number.\n";

int next, index = 0;

cin >> next;

while ((next >= 0) && (index < size))

{ a[index] = next;

index++;

cin >> next;

}

number_used = index;

}

int search(const int a[ ], int number_used, int target)

{ int index = 0;

bool found = false;

while ((!found) && (index < number_used))

if (target == a[index])

found = true;

else

index++;

if (found)

return index;

else

return -1;

}

PROGRAMMING EXAMPLE: Sorting an Array
• Sorting an array means rearranging data in a data structure to obey some order relation. An array that contains objects that can be compared is sorted if

for every pair of indices i and j. if i < j then array[i] <= array[j]

• Said differently:

a[0] <= a[1] <= a[2] <= . . . <= a[number_used - 1]

• We illustrate sorting using the selection sort algorithm in Display 9.13.
• The array is partially filled so we must pass an additional array parameter that specifies how many array elements are used.
Tests the procedure sort.

void fill_array(int a[ ], int size, int& number_used);

void sort(int a[ ], int number_used);

void swap_values(int& v1, int& v2);

int index_of_smallest(const int a[ ], int start_index, int number_used);

int main( )

{ cout << "This program sorts numbers from lowest to highest.\n";

int sample_array[10], number_used;

fill_array(sample_array, 10, number_used);

sort(sample_array, number_used);

cout << "In sorted order the numbers are:\n";

for (int index = 0; index < number_used; index++)

cout << sample_array[index] << " ";

cout << endl;

return 0;

}

void fill_array(int a[ ], int size, int& number_used)

{ cout << "Enter up to " << size << " nonnegative whole numbers.\n"

<< "Mark the end of the list with a negative number.\n";

int next, index = 0;

cin >> next;

while ((next >= 0) && (index < size))

{

a[index] = next;

index++;

cin >> next;

}

number_used = index;

}

void sort(int a[ ], int number_used)

{ int index_of_next_smallest;

for (int index = 0; index < number_used - 1; index++)

{//Place the correct value in a[index]:

index_of_next_smallest =

index_of_smallest(a, index, number_used);

swap_values(a[index], a[index_of_next_smallest]);

//a[0] <= a[1] <=...<= a[index] are the smallest of the original array

//elements. The rest of the elements are in the remaining positions.

}

}

void swap_values(int& v1, int& v2)

{ int temp;

temp = v1;

v1 = v2;

v2 = temp;

}

{ int min = a[start_index],

index_of_min = start_index;

for (int index = start_index + 1; index < number_used; index++)

if (a[index] < min)

{ min = a[index];

index_of_min = index;

//min is the smallest of a[start_index] through a[index]

}

return index_of_min;

}

Arrays of Structs( or Classes)
• An arrray with struct elements:

struct WindInfo

{

double velocity; // in miles per hour

char direction; // ‘N’, ‘S’, ‘E’, ‘W’

};

WindInfo data_point[10];

• To fill the arrrays data_point:

for (int i = 0; i < 1-; i++)

{

cout<<"Enter velocity for data point numbered: "<< i;

cin >> data_point[i].velocity;

cout<<"Enter direction for data point numbered: "<< i;

cin >> data_point[i].direction;

}

Arrays as Struct (or Class) Members
• A structure or a class can have an array as a member.
• If you have to keep track of practice times for swimming a particular distance, you might use this struct

struct Data

{

double time[10];

int distance;

};

Data my_best;

• You can use this to set the distance:

my_best.distance = 20;

• You can use this to set the time array:

cout<< "Enter ten times in seconds: \n";

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

cin >> my_best.time[i];

//Reads in 5 amounts of money and shows

//how much each amount differs from lgst

#include <iostream>

using namespace std;

#include "money.h"

int main( )

{ Money amount[5], max;

int i;

cout << "Enter 5 amounts of money:\n";

cin >> amount[0];

max = amount[0];

for (i = 1; i < 5; i++)

{ cin >> amount[i];

if (max < amount[i])

max = amount[i];

//max is the largest of amount[0],...,[i].

}

Money difference[5];

for (i = 0; i < 5; i++)

difference[i] = max - amount[i];

cout << "The highest amount is "

<< max << endl;

cout << "The amounts and their “

<<“differences from the largest “

<<“are:\n";

for (i = 0; i < 5; i++)

{

cout << amount[i] << " off by "

<< difference[i] << endl;

}

return 0;

}

Program Using an Array of Objects