Skip to Main Content
Practical C++ Programming, 2nd Edition
book

Practical C++ Programming, 2nd Edition

by Steve Oualline
December 2002
Beginner to intermediate content levelBeginner to intermediate
576 pages
14h 6m
English
O'Reilly Media, Inc.
Content preview from Practical C++ Programming, 2nd Edition

Chapter 5. Arrays, Qualifiers, and Reading Numbers

That mysterious independent variable of political calculations, Public Opinion.

Thomas Henry Huxley

This chapter covers arrays and more complex variables.

Arrays

So far in constructing our building we have named each brick (variable). That is fine for a small number of bricks, but what happens when we want to construct something larger? We would like to point to a stack of bricks and say, “That’s for the left wall. That’s brick 1, brick 2, brick 3. . . .”

Arrays allow us to do something similar with variables. An array is a set of consecutive memory locations used to store data. Each item in the array is called an element. The number of elements in an array is called the dimension of the array. A typical array declaration is:

// List of data to be sorted and averaged
int    data_list[3];

This declares data_list to be an array of the three elements data_list[0], data_list[1], and data_list[2], which are separate variables. To reference an element of an array, you use a number called the subscript (the number inside the square brackets [ ]). C++ is a funny language and likes to start counting at 0, so these three elements are numbered 0-2.

Tip

Common sense tells you that when you declare data_list to be three elements long, data_list[3] would be valid. Common sense is wrong: data_list[3] is illegal.

Example 5-1 computes the total and average of five numbers.

Example 5-1. five/five.cpp

#include <iostream> float data[5]; // data to average and ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Discovering Modern C++, 2nd Edition

Discovering Modern C++, 2nd Edition

Peter Gottschling

Publisher Resources

ISBN: 0596004192Supplemental ContentErrata Page