array what it is. how to use it how to declare it how to initialize it

24
Array • What it is. • How to use it • How to declare it • How to initialize it

Post on 20-Dec-2015

237 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Array What it is. How to use it How to declare it How to initialize it

Array

• What it is.

• How to use it

• How to declare it

• How to initialize it

Page 2: Array What it is. How to use it How to declare it How to initialize it

What is an array? Consecutive group of memory locations that all have the same name and data type

grades[0]grades[1]grades[2]grades[3]grades[4]

10085506588

name

position orsubscript

value

Page 3: Array What it is. How to use it How to declare it How to initialize it

Referencing elements in an array

grades[0]grades[1]grades[2]grades[3]grades[4]

10085506588

To calculate the sum of the first 2 elementsint sum = grades[0] + grades[1];

To change the value of the last element to 92grades[4] = 92;

position = subscript

Page 4: Array What it is. How to use it How to declare it How to initialize it

Declaring an arrayMust tell compiler name, size and data type

int grades[5];

char letters[26], numbers[10];

#define ARRAY_SIZE 5int grades[ARRAY_ SIZE];

const int array_size 5; int grades[array_size];

May only use constants to declare the size of an array.

Page 5: Array What it is. How to use it How to declare it How to initialize it

Initializing an array

int counters[5];

// Initialize array for (int i = 0; i < 5; i++) counters[i] = 0;

Note that i goes from 0 to 4 for a 5 element array not 1 to 5.

Page 6: Array What it is. How to use it How to declare it How to initialize it

Initializing an array with a declaration

int grades [5] = {100, 85, 50, 65, 88}

or

int grades [] = {100, 85, 50, 65, 88}

char numbers[] = {‘0’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’}

int n[10] = {0} // entire array is initialized to 0

Page 7: Array What it is. How to use it How to declare it How to initialize it

Common programming errors

• Forgetting to initialize an array

• Too many initializersint grades [5] = {100, 85, 50, 65, 88, 99} // error!!

• Forgetting that the subscript range is 0 to (size - 1) and not 0 to size. int grades[5];

grades[5] = 2; // error!!

Page 8: Array What it is. How to use it How to declare it How to initialize it

ExercisesAnswer the following questions regarding an array called fractions.

1) Define a constant variable array_size and initialize it to 10.

2) Declare an array with arraysize elements of type float and initialize the elements to 0.0.

3) Name the fourth element from the beginning of the array.

4) Assign the value 1.667 to the 9th element in the array.

5) Print all the elements of the array using a for repetition structure.

Page 9: Array What it is. How to use it How to declare it How to initialize it

More ExercisesFind the error in the following code segments1) int k = 4; char a1[k];

2) int a2[5] = {1, 2, 3, 4, 5, 6}

3) int a[5]; for (int i = 0; i <= 5; i++) a[i] = 0;

Page 10: Array What it is. How to use it How to declare it How to initialize it

scalability int grades[5];

// Initialize array for (int i = 0; i < 5; i++) grades[i] = 0;

// Read in 5 grades. for (i = 0; i < 5; i++) { cout << "Enter next grade: "; cin >> grades[i]; }

// Display grades for (i = 0; i < 5; i++) { cout << grades[i] << endl; }

Page 11: Array What it is. How to use it How to declare it How to initialize it

Scalability const int array_size = 5; int grades[array_size]; // Initialize array for (int i = 0; i < array_size; i++) grades[i] = 0;

// Read in 5 grades. for (i = 0; i < array_size; i++) { cout << "Enter next grade: "; cin >> grades[i]; }

// Display grades for (i = 0; i < array_size; i++) { cout << grades[i] << endl; }

Page 12: Array What it is. How to use it How to declare it How to initialize it

if (first == firstGuess) numHits++; else if ((first == secondGuess) || (first == thirdGuess)) numMatches++;

if (second == secondGuess) numHits++; else if ((second == firstGuess) || (second == thirdGuess)) numMatches++;

if (third == thirdGuess) numHits++; else if ((third == firstGuess) || (third == secondGuess)) numMatches++;What if you wanted to change the game to handle 5 or 10 letter sequences?

Compare Example

Page 13: Array What it is. How to use it How to declare it How to initialize it

Compare using arrays const int length = 3; // To handle 5 or 10 just change this char computerLetters [length]; char usersGuess[length];

int numHits = 0, numMatches = 0;

for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) {

if (computerLetters[i] == usersGuess[j]) if (i == j) numHits++; else numMatches++; } }

Page 14: Array What it is. How to use it How to declare it How to initialize it

Survey ExampleTwenty students were asked to rate the quality of the food in the cafeteria on a scale of 1 to 10 with 10 meaning excellent. Place the twenty responses in an array of integers and summarize the results of the poll.

Initialize responses array with student’s responses.

Create another array to use to summarize their responses. subscript 1 in the array will contain a count of the number of students responses = 1, subscript 2 will contain a count of the number of student responses = 2, etc.

Display responses in a table with 2 columns: Rating Frequency

Page 15: Array What it is. How to use it How to declare it How to initialize it

Survey code const int numResponses = 20; const int maxRange = 10; int responses [numResponses] = {1, 2, 6, 4, 8, 5, 9, 7, 10, 6, 5, 8, 7, 3, 4, 6, 7, 8, 5, 6}; int frequency[maxRange + 1] = {0}; int pos;

for (pos = 0; pos < numResponses; pos++) { frequency[responses[pos]]++; }

cout << "Rating " << " Frequency" << endl; for (pos = 1; pos <= maxRange; pos++) { cout << setw(3) << pos << setw (11) << frequency[pos] << endl; }

Page 16: Array What it is. How to use it How to declare it How to initialize it

survey code scalability

• To change number of students surveyedconst int numResponses = 40;

• To change scale of responses from 1 to 10 to 1 to 5. const int maxRange = 5;

Page 17: Array What it is. How to use it How to declare it How to initialize it

ExerciseChange the survey code to also print a histogram as follows: Rating Frequency Histogram 1 1 * 2 1 * 3 1 * 4 2 ** 5 3 *** 6 4 **** 7 3 *** 8 3 *** 9 1 * 10 1 *

Page 18: Array What it is. How to use it How to declare it How to initialize it

arrays as function parameters

• pass the name of the array without any brackets.

• pass array size (optional)

• always passed by reference

Page 19: Array What it is. How to use it How to declare it How to initialize it

arrays as function parametersPass the name of the array without the brackets

void PrintResults(int results[ ]); // function prototype

void PrintResults(int results[ ]) // function definition{

}

calling sequence: const int maxRange = 10; int frequency[maxRange + 1] = {0}; PrintResults (frequency);

Page 20: Array What it is. How to use it How to declare it How to initialize it

arrays as function parametersPass array size

void PrintResults(int results[ ], int size);

void PrintResults(int results[ ], int size) { cout << "Rating " << " Frequency" << endl; for (int pos = 1; pos <= size; pos++) { cout << setw(3) << pos << setw (11) << results[pos] << endl; }}calling sequence: const int maxRange = 10; int frequency[maxRange + 1] = {0}; PrintResults (frequency, maxRange);

Page 21: Array What it is. How to use it How to declare it How to initialize it

arrays as function parametersalways passed by referencevoid PrintResults(int results[ ], int size);

void PrintResults(int results[ ], int size) { results[5] = 10; // does change caller’s data }calling sequence: const int maxRange = 10; int frequency[maxRange + 1] = {0}; PrintResults (frequency, maxRange); cout << results[5] << endl; // displays 10;

Page 22: Array What it is. How to use it How to declare it How to initialize it

Use const to prevent function changes

void PrintResults(const int results[ ], int size);

void PrintResults(const int results[ ], int size) { results[5] = 10; // compiler error!! }

calling sequence: // this doesn’t change const int maxRange = 10; int frequency[maxRange + 1] = {0}; PrintResults (frequency, maxRange);

Page 23: Array What it is. How to use it How to declare it How to initialize it

Entire arrays are passed by reference but not single elements

const int maxRange = 10; int frequency[maxRange + 1] = {0};

void PrintResults( int results[ ], int size); calling sequence: PrintResults (frequency); results array was passed by reference. PrintResults could change it.

void PrintResults (int element); calling sequence: PrintResults (frequency[4]); The 5th element of the array was passed by value not by reference. PrintResults cannot change it.

Page 24: Array What it is. How to use it How to declare it How to initialize it

Exercises

1) Write a function called FindAverage that accepts an array of integers as an input parameter and returns the average.

2) Find the errors in the following code:int PrintSum( const int values[ ], int size) { int sum = 0; for (int i = 0; i < size; i++) { sum += values[i]; } values[0] = 100; values[size] = sum; }