C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

So this program is designed to show you two different ways you can add values to a variable array.
It’s a bit impersonal, so if you wanted, you could add a string array for the player’s name at the
beginning of the program; then the prompts for the individual game scores and the final average could
incorporate that name. In the next two chapters, you learn how to search an array, as well as sort the
data in the array, in case you want to list the player’s scoring from best to worst.


Warning

Don’t make the same mistake we made. The first time we ran the program, we got a
scoring average of 42,000 per game (which we are fairly certain would be a record for
an individual player). Why did this happen? When we defined the variable
totalPoints, we did not set it to 0 initially, and as we’ve reminded you throughout
the book (but did not apply to our own program), you cannot assume that, just because
you define a variable, it is initially empty or 0.

The Absolute Minimum
The goal of this chapter was to teach you how to store data in lists called arrays. An
array is nothing more than a bunch of variables. Each variable has the same name (the
array name). You distinguish among the variables in the array (the array elements) with
a numeric subscript. The first array element has a subscript of 0, and the rest count up
from there.
Arrays are characterized by brackets that follow the array names. The array subscripts
go inside the brackets when you need to refer to an individual array element. Key
concepts from this chapter include:


  • Use arrays to hold lists of values of the same data type.

  • Refer to the individual elements of an array with a subscript.

  • Write for loops if you want to “step through” every array element, whether it be to
    initialize, print, or change the array elements.

  • In an array, don’t use more elements than defined subscripts.

  • Don’t use an array until you have initialized it with values.

Free download pdf