A one-dimensional array is a data type that allows us to allocate a group of similar elements all at once and to give them a single name. For example, the declarations
int A[10]; float nums[15]; /* 0 1 2 3 4 5 6 7 8 9 ------------------------------- A | | | | | | | | | | | ------------------------------- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ---------------------------------------------- nums | | | | | | | | | | | | | | | | ---------------------------------------------- */
create an array named A that holds 10 integer variables (numbered 0 to 9) and an array named nums that holds 15 floating-point variables (numbered 0 to 14). Each element of the array A is an integer variable and each element of nums is a floating-point variable. To refer to an individual member of an array we use the square-bracket form. For example A[4] is the element numbered 4 in the array A and nums[10] is the element numbered 10 in the array nums.
An interesting aspect of arrays is that the number between the square brackets does not have to be a literal constant. We can use any expression that evaluates to an integer value. For example, A[I] would be the element from the array A corresponding to value of the integer variable I (if I is 5, A[I] is the element numbered 5 in A).
We can use this aspect of arrays to write loops that allow us to process ALL of the elements of an array with a single loop. There are two basic types of loops we use to process the elements of an array:
Processing ALL of the elements of an array: do initital setup for (I = 0; I < ARRAYSIZE; I++) process ARRAYNAME[I] post process
or
Searching for AN element of an array: do initial setup I = 0; while ((I < ARRAYSIZE) && (ARRAYNAME[I] is not the element we are looking for)) I++; if (I < ARRAYSIZE) element is found at I else element is not found
In this lab we are going to get some experience with processing an array.
The following program reads in a group of values using a process all loop. To this program we want to add two processes: (1) a loop to calculate the sum of all the values (in order to produce the average); and (2) a loop to find the first value in the array that is below the average.
#include <stdio.h> #include <stdlib.h> void main() { int I; float nums[15]; float total = 0.0; float average; for (I = 0; I < 15; I++) { printf("Please enter number %d: ",I+1); scanf("%f",&(nums[I])); } /* Add a loop to sum up all of the numbers in the variable total */ average = total / 15; /* Add a loop to find the first member of the array that has a value that is below the average */ }
Turn in a hard copy of your final program. Also, turn in a copy of output for your program showing that it works correctly.