Chapter 7. Storing Sequences in Arrays

In This Chapter

  • Considering the need for something like an array

  • Introducing the array data type

  • Using an array

  • Using the most common type of array — the character string

An array is a sequence of variables that shares the same name and that is referenced using an index. Arrays are useful little critters that allow you to store a large number of values of the same type that are related in some way — for example, the batting averages of all the players on the same team might be a good candidate for storage within an array. Arrays can be multidimensional, too, allowing you, for example, to store an array of batting averages within an array of months, which allows you to work with the batting averages of the team as they occur by month.

In this chapter, you find out how to initialize and use arrays for fun and profit. You also find out about an especially useful form of array called a char string.

Arraying the Arguments for Arrays

Consider the following problem. You need a program that can read a sequence of numbers from the keyboard and display their sum. You guessed it — the program stops reading in numbers as soon as you enter a negative number. Unlike similar programs in Chapters 5 and 6, however, this program will output all the numbers entered before displaying the average.

You could try to store numbers in a set of independent variables, as in

cin >> value1;
if (value1 >= 0)
{
    cin >> value2;
    if (value2 >= 0)
    {
            ...

You can see that this approach can't ...

Get C++ For Dummies®, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.