TA: Brian Choi (schoi@cs.ucla.edu)
Section Webpage:
http://www.cs.ucla.edu/~schoi/cs31
Arrays
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:
int a[100];
// declaration
This will create an
array
of integers of length 100, where each item in the array can be referred to as:
a[i]
where
i
is the
index
ranging from 0 to 99, or 0 to length-1. (Does this sound familiar?)
a[i]
is an integer
variable, and happens to be in the location
i
of the array
a
.
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[3] = 5;
x[1]++;
cout << x[i] << endl;
CS31: Introduction to Computer Science I
Spring 2011
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 main()
{
int sums[100]; // This is our array, creating 100 adjacent variables.
for (int i = 0; i < 100; i++)