You are on page 1of 6

Arrays Objective #1: Be able to declare and initialize arrays.

An array is a list of variables that are referred to with the same variable name (identifier.) To declare an array before it is used in the body of your program, you must use a statement like: int scores[10]; which would declare an array of integers, which is named "scores". In this case, scores can store up to 10 different integer values. The positions of the array are identified by their index positions which run from 0 to 9 (not 1 to 10.) Each one of the 10 variables in scores is called an element. You could also store doubles in an array or any other primitive data type. You simply have to declare the array appropriately. For example, the following declaration would declare an array of doubles: double sums[20];

If you wish to initialize each element of an array to a specific value, you can use the statement, int scores[5] = {65, 76, 45, 83, 99}; You don't even have to specify a size of the array in this case since the initialization statement int scores[] = {65, 76, 45, 83, 99}; would cause the compiler to declare an array of size 5 since there are five values in the set of curly braces.

Be careful not to attempt to access an index position that is not actually part of an array. If you initialize the array, scores, to the size of 10 but then attempt to assign a value to the fifteenth index position of scores, you may not experience a syntax or run-time error. Rather, you may accidentally overwrite another variable. When you visualize an array or represent it on paper, you might think of it like this: int scores[5] = {65, 76, 45, 83, 99}; scores

index position element's value

65

76

45

83

99

Objective #2: Be able to use arrays with assignment statements.

An element of an array can be assigned a specific value using the assignment operator ( = ). For example, the following assignment statement assigns the value 99 to index position 3 of an array named scores: scores[3] = 99; Note that the value 99 is really stored in the fourth element of the array scores since the first element has index position 0.

The following assignment statement would cause an error since the array is declared to a size of 5 and there is no index position 5. int scores[5]; // scores has 5 elements with index positions 0 thru 4 scores[5] = 99; // this assignment statement causes an error

Objective #3: Be able to use loops in conjunction with arrays to allow the user to input data into an array and be able to use loops with arrays to display data stored in an array.

The following determinate for loop can be used to allow the user to input values into an array. A running total of the inputed values is also obtained and then the average of those inputed numbers is displayed. int sum = 0; int num[5]; int i = 0; for (i = 0; i < 5; i++) { cin >> num[i]; sum = sum + num[i]; } cout << "The average is " << double (sum) / i << endl;

Note that the double typecasting operator must be used here to avoid truncation due to integer division. You should also realize that the variable i is 5 when the division occurs even though the last value was stored in the element num[4]. Objective #4: Identify when to use parallel arrays and be able to use them effectively to store related sets of data.

Sometimes, two one-dimensional arrays are used together to tie two sets of data together. For example, you can store 5 student ID numbers in a one-dimensional array of integers, while storing the grades of the same 5 students in an array of doubles. As long as the student grades are sorted in the same representative order as the student ID numbers, one can use the two arrays as parallel arrays. This allows the same index position to refer to a given student's ID number and his/her grade by accessing the appropriate elements of the two arrays. int studentID[5] = {112, 324, 981, 548, 823}; double studentGrades[5] = {88.7, 79, 87, 93.1, 65}; int num = 0; cout << "Enter the student ID of the student whose grade you would like to look up: "; cin >> num; for (i = 0; i < 5; i++) { if (studentID[i] == num) { cout << "Student #" << studentID[i] << "'s grade is " << studentGrade[i] << endl; } }

Objective #5: Understand sequential searching and be able to search a onedimensional array for a given key.

Although there are more efficient ways to search for data, sequential searching (aka linear searching) is a good choice, especially when amount of data to be searched is small. Using a loop, you simply check each element of an array with an if statement position by position until you find the one that you are looking for. You can use an indeterminant while loop or a determinant for loop if you know the length of the array.
int numbers[10] = {2, 3, 54, 12, 22}; bool found = false;

int key = 0; cout << "What value would you like to search for? "; cin >> key; while (!found) { if (numbers[position] == key) { cout << "Found it in position " << position; found = true; } position++; }

or
int numbers[10] = {2, 3, 54, 12, 22}; int key = 0; cout << "What value would you like to search for? "; cin >> key; for (int i = 0; i < 5; i++) { if (numbers[i] == key) { cout << "Found it in position " << i; break; } }

The material below this point may not be included in this course or any exams. See the instructor for clarification. Objective #6: Understand binary searching.

If the data is ordered (alphabetically for example) in an array then a binary search is much more efficient than a sequential search. For example, if you were searching for a given number in an array of 100 sorted integers, you would only need a maximum of 7 guesses to find the number if it is present in the array. With a sequential search, in the worst case scenario, you would need 100 guesses since the value that you are searching for could be in the very last position of the array.

In the case of a binary search, you first examine the "middle" element. If that element is "lower" (alphabetically, for example) than the element which you are looking for, then you discard the lower half of the data and continue to search the upper half. The process repeats itself when you then look at the middle element of the remaining "upper half" of the data.
while (low <= high && !found) { mid = (low + high) / 2; if (key > numbers[mid]) { low = mid + 1; } else if (key < numbers[mid]) { high = mid - 1; } else { cout << "The value" << key << " was found in position " << mid; found = true; } }

Objective #7: Be able to use two-dimensional arrays.

Arrays of more than one dimension can be used to arrange more complicated sets of data. Two-dimensional arrays are used quite often. For example, a spreadsheet can be thought of as 2-dimensional array (sometimes called a table.) The same variable name (that is, identifier) is used to access each element of the 2dimensional array but the proper index position subscripts must be used. To declare an array of integers called studentGrades to be a 2-dimensional array with 3 rows and 4 columns, you would use the statement: int studentGrades[3][4]; where the first integer value is used to specify the number of rows in the array and the second value specifies the number of columns. I think of RC Cola to remember that the number of rows must be specified first and the number of columns second.

You can initialize the 2-dimensional array when you declare it by using commas and braces appropriately. For example, int studentGrades[3][4] = {

{ 1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 11, 12} };

Be careful though when assigning values to a specific position within a 2dimensional array. Keep in mind that just like one-dimensional arrays, the subscript positions with regard to the rows and the columns begin at 0, not 1. In the example above the value of the element studentGrades[0] [2] is 3.

Objective #8: Be able to interpret and use double-nested loops to effectively display the elements of a two-dimensional array.

A two dimensional array can be obtained as input and displayed as a table or matrix using double nested loops. int row = 0; int column = 0; int studentGrade[5][3]; for (row = 0; row < 5; row++) { for (column = 0; column < 3; column++) { cin >> studentGrade[row][column]; cout << studentGrade[row][column] << '\t'; } cout << endl; } The use of '\t' causes the elements to be neatly separated by tabs. The cout << endl; statement separates the rows.