One-Dimensional Arrays All data in a C++ program is stored in a data structure. In previous programs, you stored most of your data in structures called variables that were of type int and float. The basic data types are called primitive data structures. You have also used arrays of characters to store string data. A character array is one example of a category of data structure called simple data structures.You will also learn the difference between one-dimensional arrays and multi-dimensional arrays. Arrays may be of any data type and used for many purposes within your programs. DECLARING ONE-DIMENSIONAL ARRAYS Recall that when you declared a one-dimensional character array, you used statements like the one below. Char name[21]; The syntax for declaring arrays of types other than char is the same, except for the data type. Below is a declaration for an array of floats. The number in the brackets instructs the compiler to set aside memory for a given number of floating-point numbers (in this case 20 numbers). The array is just like a list of variables that share the same name. Each variable in the array is called an element. Most arrays of characters are used to store strings. When you intend to store a string in a character array, you declare one more element than the number of printable characters in your string. As you know, the extra element is for the null terminator. Arrays that store values other than strings are declared for the exact number of elements needed. For example, all 20 elements of array x, declared above, can be used for floating-point numbers. WHEN ARE ARRAYS NEEDED? Using an array of characters makes sense, but why would you want to store an array of integers or floating-point numbers? Actually, you will find lots of uses for arrays of data other than characters. Let's look at some examples. Suppose you want to write a program that stores the high temperature for every day of the month and then calculates an average. You could use a 31-element array, like the one declared below, to store the high temperature for every day of any given month. Int daily_temp [31]; Let's look at another example. Suppose you have written a computer game and you want to display the ten highest scores between games. The array declaration below could hold the scores. The statement declares a ten-element array of unsigned long integers. Unsigned long score [10]; The contents of the score array are lost when the user quits the game. Therefore, the ten highest score would resent every time the game is loaded into memory. In an upcoming chapter, however, you will learn how to save data such as high scores to disk so that they can be reloaded every time the game is played. INITIALIZING AND ACCESSING THE ELEMENTS OF AN ARRAY You can initialize arrays with values when you declare the array The statement below declares and initializes an array. Unsigned int distance[5] = {458, 288, 5O6, 379, 490}; Recall that you have created character arrays without specifying the length of the array. You can do the same thing with any array when it is declared. The statement below creates the same array as the statement above. Unsigned int distance[] = {458, 288, 506, 379, 490}; When you declare an array without providing a subscript, its size is initialized to the number of values contained in the braces. Be sure the number of values in the braces is sufficient to hold the maximum number of elements in your array. Most arrays are initialized while the program is running. Once an array is declared, elements must be accessed individually to change their values. Each element is accessed using subscript notation, which you used to access individual characters of a character array in Chapter 10. Recall that a 20-element array is accessed using the subscripts 0 through 19. For example, the first element in the array declared as float x[20], is accessed using x[0]. The final element in the array is x [19]. The compiler will not prevent you from assigning a value to x[20] or even x[100]. Those subscripts will access memory locations outside of your array. Assigning values to subscripts outside of your array will overwrite other data in memory. Address 201248 [458] distance[0] 201249 201250 [288] distance[1] 201251 201252 [506] distance[2] 201253 201254 [379] distance[3] 201255 201256 [490] 201257 distance[4] FIGURE 11-1 This one-dimensional array has five elements. Figure 11-1 shows how the array related to distance declared earlier is stored in memory The actual memory addresses are not important, and will vary Because of the data type selected, each element takes two bytes of memory (On some systems, unsigned ints may occupy four bytes.) The array is accessed using subscripts 0 through 4. The code below uses an integer variable named index to access the elements of the distance array and initialize the elements with values from the user. Int index; For {index = 0; index <= 4; index++) Cin >> distance[index]; The same kind of loop can be used to print the values in the array to the screen, as shown below: For {index = 0; index <= 4; index++) Cout << distance[index] << '\n'; The program in Figure 11-2 illustrates a simple array The array named num has three elements. The array is accessed using the subscripts 0, 1, and 2. ==================================================================== SIMPLE ONE-DIMENSIONAL ARRAY For practice enter the program in Figure 11-2. Save the source code as INTARRAY.CPP. #include void main() { int num[3]; num[0] = 12; num[1] = 16; num[2] = 32; cout << num[0] << ' ' << num[1] << ' ' << num[2] << endl; } FIGURE 11-2 This simple program uses a three-element array. ========================== Program Hightemp A ONE-DIMENSIONAL ARRAY EXAMPLE The program in Figure 11-3 uses a one-dimensional array to store high temperatures for a series of days. At the end of the program, the temperatures are printed back to the screen and averaged. Let's examine the program. The program first declares a constant and the variables it needs. The array-size constant is used to declare the array. Having the value in a constant makes the size of the array available later in the program. The constant will be used to make sure that the number of values the user wants to enter will fit in the array. The prompt for num_values is in a do while loop so that the prompt can repeat until the user enters a valid number. The first for loop (repeated below) prompts the user for each of the daily high temperatures. Even though the array subscripts range from 0 to 31, this program begins with subscript 1. Beginning with subscript 1 allows the array subscripts to correspond directly with the day number. The drawback to this approach is that one element of the array is never used. For (index=1; index <= num_values; index++) { cout << "Enter the high temperature for day " << index << ": "; cin >> daily_temp[index]; // input value into array } The program's second for loop (repeated below) prints the values in the array to the screen, and totals the values in the same loop. The total will be used after the loop to calculate the average temperature. For (index = 1; index <= num_values; index++) { cout << "Day " << index << ": " << daily_temp[index] << endl; total = total + daily_temp[index]; // update total for averaging } When the temperatures are averaged, total and num_values (which are both ints) are typecasted to floats so that the average will be a floating-point number. In the exercise that follows, you will compile and run the program from program Hightemp. ============== EXERCISE 11 ONE-DIMENSIONAL ARRAYS 1. Type in the following program correcting errors and filling in the correct identifiers when asked. 2. Compile and run the program. Test the program by providing about five temperatures as input. Make sure you understand how it works. 3. Run the program again. When prompted for the number of days for which you have data, enter a value less than 1 or greater than 31. The program should prompt you to enter a valid value. Enter a valid value and complete the session with the program. ============ // HIGHTEMP // This program averages the high temperatures over a user-defined // number of days. #include #include void main() { const mt array_size 32; int daily_temp[array_size]; int num_values; int index; float average_high; int total = 0; do // loop to ask for number of days until valid input is received { cout << "Enter the number of days for which you have data: "; cin >> num_values; if ((numvalues < 1) || (num_values > array_size - 1)) { cout << "The number of days must be in the range 1 to " << array_size - << endl; } } while ((num_values < 1) || (num_values > array_size - 1)); // The following loop gets the high temperatures fros: the user for as // many days as the user specified in num_values. The subscript 0 is // not used so that the subscript will correspond with the day number. for(index = 1; index <= num_values; index++) { cout << "Enter the high temperature for day " << index << ": "; cin >> daily_temp[index]; } // Print the values in the array to the screen. cout << "The array contains high temperatures for " << num_values << " days.\n"; cout << "The values are as follows.\n"; for(index = 1; index <=num_values; index++) { cout << "Day " << index << ": " << daily_temp[index] << endl; total = total + {fill me in}; //update total for averaging // Calculate average by typecasting total and num_values to floats // before dividing and assigning the result to average_high. average_high = (float) total / (float) {fill me in}; // Print the results to the screen. cout << "The average high temperature during the " << {fill me in} << "-day period was " << setprecision(2) << {fill me in} << " degrees.\n"; } FIGURE 11-3 This program uses an array of integers to store high temperatures for a series of days.