TA: Brian Choi (firstname.lastname@example.org)
Suppose you want to create 10 integer variables. Using what we know, we can do the following:
int x1, x2, x3, x4, .
.. , x10;
That is long, but still doable. What if, though, we want to make 100 of them, or 1000 of them? C++
provides a simple way of creating variables of the same type in a single statement. This is how:
This will create an
of integers of length 100, where each item in the array can be referred to as:
ranging from 0 to 99, or 0 to length-1. (Does this sound familiar?)
is an integer
variable, and happens to be in the location
of the array
When you declare an array, you must specify the size of the array you’re declaring, and the size must be a
positive integer constant
. A constant is either a value itself (e.g., 5, 10, 100) or a variable that is explicitly
declared to be a constant (e.g.,
const int N = 10;
), such that the value of it can’t be changed.
An example helps you understand how this works. What does the following program do?
You can treat each element of the array as if it were a variable (since it IS a variable). You can therefore do:
x = 5;
cout << x[i] << endl;
CS31: Introduction to Computer Science I
Copyright Brian Choi 2011. All Rights Reserved.
Week 5, Page 1/4
int sum(int m, int n); // sum from numbers m to n
int sums; // This is our array, creating 100 adjacent variables.
for (int i = 0; i < 100; i++)