Looping through Arrays

Obviously if you have an array of any substantial size, then working with its individual elements—as in the previous examples—quickly becomes tedious. This is even truer if the same process is used on each value (printing it, performing calculations with it, and forth). The easiest way to access every array element is to use a for loop.

You can review Chapter 4, “Control Structures,” for the syntax of a for loop, but normally there are four parts (Figure 6.6). The loop first initializes a variable to a value, and then checks that variable against another value as its condition. If that condition is true, certain statements are executed. Finally, the variable is incremented.

Figure 6.6. This flowchart reflects how for loops function.


When working with an array, you'll want to use the variable to represent all of the array's indexes, from 0 (the first element) to NUM - 1, where NUM is the number of elements in the array. You'll need to subtract 1 because if an array has NUM elements, there is no element indexed at NUM (because counting starts at 0).

The basic code, then, is

int i;
const int NUM = 10;
int my_array[NUM];
for (i = 0; i < NUM; i++) {
  /* Do something with my_array[i]. */
}

With this in mind, the exchange application will be modified so that it creates an array of dollar amounts using a loop.

To loop through an array

1.
Open exchange.c (Script 6.4) in your text editor or IDE, if it is not already open.

2.
Add a new variable for the loop (Script 6.5):

unsigned int i;

Script 6.5. This for loop, along with the NUM constant and the i index variable, accesses every array element.


The i variable is a simple unsigned integer. It will be used as the array index variable within the for loop.

3.
Print two header lines that will describe the forthcoming table:

printf ("US Dollar to Mexican Pesos
 converter:

");
printf ("%10s %10s
", "Dollars",
 "Pesos");

Like the tips calculator in the last chapter, this application will print a table of values. To help it lay out nicely, some padding in the printf() statement creates spacing. Here, two strings are printed (Dollars and Pesos), each using a total of 10 spaces.

4.
Begin defining the for loop:

for (i = 0; i < NUM; i++) {

This loop begins by setting the i variable to a value of 0. That number corresponds to the first index in the array. Then the conditional checks to see if i is less than NUM, which was defined earlier as a constant. As there are NUM elements in the array, the last element is indexed at NUM - 1. Therefore, as long as i is less than NUM, amounts[i] is a valid reference. The third part of the loop increments i by 1.

5.
Set the value of the array for each element:

amounts[i] = (i + 1) * 5.00;

The first statement within the loop assigns a value to the array element. Since the loop iterates through the entire array using i, this line will populate the entire array. The value itself is calculated as the sum of i + 1 multiplied by 5.00. The end result will be an array of five-dollar increments, from 5.00 to NUM * 5.

6.
Print the original amount and the converted amount:

printf ("%10.2f %10.2f
",
 amounts[i], (amounts[i] *
 1.317466));

This conversion turns U.S. dollars (the original array values) into Mexican pesos, using the current exchange rate at the time of this writing. Again, formatting is used within the printf() statement so that the table is more legible.

7.
Complete the for loop syntax:

} // End of for loop.

8.
Save the file as exchange2.c, compile, and debug as necessary.

9.
Run the application to see the results (Figure 6.7).

Figure 6.7. An array and a loop helps to create this table of numbers.


10.
Change the value of NUM, recompile, and rerun the application (Figure 6.8).

Figure 6.8. Changing just one simple value—the NUM constant in Script 6.5—creates different results (compare with Figure 6.7).


✓ Tips

  • The exchange example as written does not need an array at all, since nothing is done with amounts after its values are set. But if you wanted to, for example, create a separate table showing exchange rates for a different currency, you could add another for loop that performs and displays that calculation using the same amounts array.

  • When using loops to work with arrays, it's easy to create an Off-By-One-Bug. Remember that the highest index in an array is 1 less than the number of elements in the array (because arrays are indexed starting at 0). For this reason, the condition in the loop is i < NUM and not i <= NUM.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset