arrays. one dimensional arrays a data structure used for storage of a collection of data items that...

56
Arrays

Upload: maximillian-doyle

Post on 23-Dec-2015

222 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 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

Arrays

Page 2: 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

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.

Page 3: 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

Declaring Arrays

Assign one variable name to a collection of two or more adjacent memory cells. Must declare:

type array-name [size];

Page 4: 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

Declaring Arrays

Examples:

double temperature [5];

Page 5: 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

double temperature [5];

7.5

65.0

72.1

87.5

12.3temperature [0]

temperature [1]

temperature [2]

temperature [3]

temperature [4]

Page 6: 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

double temperature [5];

Elements

7.5

65.0

72.1

87.5

12.3temperature [0]

temperature [1]

temperature [2]

temperature [3]

temperature [4]

Page 7: 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

double temperature [5];

7.5

65.0

72.1

87.5

12.3

SubscriptorIndex

temperature [0]

temperature [1]

temperature [2]

temperature [3]

temperature [4]

Page 8: 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

Printing the Array

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

Page 9: 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

Printing the Array

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

{

cout<<temperature[i]<<endl;

}

Subscript Variable

Page 10: 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

Assignment Statement

temperature [4] = 12.7;

or

N = 4;temperature [N] = 12.7;

Page 11: 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

1. Use assignment statements

2. Initialize arrays in the variable declaration statement

3. Read input values into the array from the keyboard or from a file

Three ways to get values into array elements

Page 12: 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

Reading Arrays

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];

Page 13: 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

Average Temperature

double sum = 0.0;

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

{

sum += temperature[i];

}

average = sum / 5.0;

Page 14: 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

More About Array Declarations

We may use constants for the size in an array declaration:

const int SIZE = 6;

int score[SIZE];

Page 15: 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

declaration:

int score [6];

score:

index: 0 1 2 3 4 5(Subscript)

49 75 65 90 77 70

score[2] = 65;score[0] = 49;

Page 16: 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

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

Page 17: 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

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];

Page 18: 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

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;

Page 19: 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

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.

Page 20: 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

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};

Page 21: 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

Array Practice1. Declare an array to hold the tax for up to 10 different sales.

2. Declare an array to hold the final letter grades for a class with up to 40 students

3. Declare an array of integers which holds the final average for those 40 students and initialize its values to 0

4. Declare an array of characters called letter_ary with initial values ‘a’, ‘d’, ‘y’, and ‘w’. What is the value of letter_ary[1]?

Lec p. 132

Page 22: 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

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];

}

3. Enter from keyboard or file

Page 23: 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

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.

Lec p. 133

Page 24: 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

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.

Page 25: 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

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 sizefor( int i = 0; i < n; i++)

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

}

Must be a constantMust be a constant

Page 26: 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

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;}

Page 27: 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

Dice Example

Write a C++ program to find the frequency distribution of all possible sums of the roll of two dice.

Page 28: 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

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

Page 29: 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

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

Page 30: 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

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]); function header:

void modifyElement(int num) {

Page 31: 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

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); Call:

ReadScore(score, NumPlayers); Header: void ReadScores(int score[], int NumPlayers);

Page 32: 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

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]);

}}

Page 33: 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

Note! We cannot return 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);

Page 34: 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

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

Page 35: 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

Parallel Arrays

ID_arr:

index: 0 1 2 3 4 5

222 123 445 346 771 708

avg_arr:

index: 0 1 2 3 4 5

87.5 75.2 94.0 90.0 77.9 83.9

grade_arr:

index: 0 1 2 3 4 5

B C A A C B

Page 36: 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

Arrays of Structures

struct StudentInfo{ int stu_id; double avg; char grade;}

to declare:StudentInfo Our_class[40];

to use members:

Our_class[1].stu_id = 123;

Our_class[0].grade = ‘A’;

Page 37: 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

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.

Page 38: 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

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.

Page 39: 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

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.

Page 40: 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

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.

Page 41: 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

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;}

Page 42: 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

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;

}

Page 43: 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

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;

}

}

Page 44: 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

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;}

Page 45: 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

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;}

Page 46: 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

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;}

Page 47: 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

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;}

Page 48: 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

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.

Page 49: 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

Selection Sort

Page 50: 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

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;}

Page 51: 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

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;}

Page 52: 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

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;}

Page 53: 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

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

{ 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;}

Page 54: 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

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; }

Page 55: 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

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];

Page 56: 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

Program Using an Array of Objects//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;}