C++ Arrays and Loops
September 11, 2018
In this tutorial, you’ll learn about arrays and loops in C++. Both of these are very important concepts in programming. In plain English, loop-statements correspond to “Do this action X times.” or “Keep doing that action as long as this condition is true.” But let’s learn about arrays first.
Arrays
The variables you saw so far in the course only stored a single number or string. What if we wanted to store multiple numbers or strings? This is exactly what an array does.
Arrays are collections of values of a single type stored together (we cannot have an array containing numbers and strings together). In this article, you will learn to declare, initialize and access array elements.
Declaring an array
Suppose you are taking a survey of 100 people and you have to store their age. To solve this problem in C++, you can create an int
array with 100 elements. For example:
int age[100];
In general, the syntax for declaring an array is:
data_type array_name[array_size];
The size and type of an array cannot be changed after declaration.
Declaring an array with initialization
It’s possible to initialize an array during declaration. For example, let’s create an array of lottery numbers:
int lottery[6] = {3, 42, 12, 19, 30, 59};
Since we are initializing all the values, C++ can automatically infer the size of the array. Hence, we can also initialize the above array without explicitly specifying the size:
int lottery[] = {3, 42, 12, 19, 30, 59};
How to access array elements?
You can access an array element by its index. An index is the number that says where in an array an item occurs. In programming, we prefer to start counting at 0, so the first object in your array is at index 0, the next one is at 1, and so on.
Hence, for the array in the previous section:
lottery[0] is 3
lottery[1] is 42
lottery[2] is 12
lottery[3] is 19
lottery[4] is 30
lottery[5] is 59
Since the first index is 0, the last element has index 5. In general, if the size of an array is n, the index of the last element is (n-1).
int lottery[6] = {3, 42, 12, 19, 30, 59};
Array index is written at the bottom (in black) and corresponding values are shown on top
Let’s try printing and updating the array elements.
int lottery[6] = {3, 42, 12, 19, 30, 59};
// print first element of an array (index 0)
cout << lottery[0] << endl;
// Output - 3
// print the last element of an array (index 5)
cout << lottery[5] << endl;
// Output - 59
// update the value at index 3
lottery[3] = 17;
// array is now {3, 42, 12, 17, 30, 59};
// take input from the user and insert at third element (index 2)
cin >> lottery[2]; // Suppose the input is 9
// array is now {3, 42, 9, 17, 30, 59};
Note: If you try to access array elements outside of its bound, let’s say
lottery[8]
, the compiler may not show any error. However, this may cause unexpected output (undefined behavior).
Multi-Dimensional Arrays
C++ also supports multi-dimensional arrays. Here’s an example of a 2-dimensional array of size 3 x 4.
int x[3][4];
Below is a visualization of the 2-dimensional array. It’s just a grid of numbers, where the first number is the row index, and the second number the column index.
Visualization of 2-dimensional array x[3][4]
In general, the syntax for defining a N-dimensional array is:
type name[size1][size2]...[sizeN];
As before, you can initialize the array values are the time of declaration. Following is an array with 2 rows and 3 columns:
int x[2][3] = {
{2, 3, 4}, // 1st row
{8, 9, 10} // 2nd row
};
From the above initialization, you can see that a 2D array is simply an array of arrays. You can also write the same initialization in one line.
int x[2][3] = {{2, 3, 4}, {8, 9, 10}};
The elements of a 2D array are accessed by using the row index and column index of the element. For example:
int x[2][3] = {{2, 3, 4}, {8, 9, 10}};
cout << x[0][2] << endl;
// Outputs - 4
We can do more with arrays, but to do that, we need to learn about loops.
Loops
Programmers don’t like to repeat themselves. Programming is all about automating things, right? That’s where loops come in handy.
The general syntax of a for-loop is:
for (initialization; condition; update) {
.. statements (loop body) ..
}
Hence, the above program translates to:
- Execute initialization statement
- Check if condition is true
- If condition is not true, stop immediately. (for loop execution has finished.)
- Execute the statements in the loop body.
- Execute update statement
- Go to step 2 and repeat.
Let’s see this in action with an example. Below is a for loop to print numbers from 1 to 10:
for (int a = 1; a <= 10; a++) {
cout << a << endl;
}
Output:
1
2
3
4
5
6
7
8
9
10
Let’s see what is going on in the program above.
- First,
a
is initialized to1
. - Then, the condition
a <= 10
is checked, which istrue
. - So the loop body (
cout << a << endl;
) gets executed, which prints the value ofa
, i.e. the number1
gets printed. - The update statement
a++
is executed, which changesa
’s value to2
. Note thata++
is just shorthand fora = a + 1
ora += 1
. - Since the condition
a <= 10
is still true, the loop body prints the current value ofa
which is equal to2
. Then, the value ofa
is updated to3
. - This repeats for
a
=4
,5
,6
, up to10
. - Finally, when
a
’s value is updated to11
, the conditiona <= 10
is nottrue
anymore, and the loop execution stops.
Congratulations on your first loop! You’ll be writing many more of them!
Iterating over array elements
Now, let’s see an example which involves loops as well as arrays. Still remember arrays? Let’s do an array of people:
string people[5] = {"Rachel", "Monica", "Phoebe", "Ola", "You"};
We want to greet all of them by their name.
Let’s use for
loop to greet them:
string people[5] = {"Rachel", "Monica", "Phoebe", "Ola", "You"};
for (int i = 0; i < 5; i++) {
cout << "Hi " + people[i] + "!" << endl;
cout << "Next Person" << endl;
}
And when we run it:
Hi Rachel!
Next person
Hi Monica!
Next person
Hi Phoebe!
Next person
Hi Ola!
Next person
Hi You!
Next person
Awesome isn’t it? We used a for-loop to iterate over values i = 0, 1, ..., 4
and for each value of i
we said “Hi!” to people[i]
.
Calculating sum of elements in an array
For loops can be used for all sorts of things. Let’s conclude this section by writing a program to store an array of 5 numbers, and then calculate the sum of the numbers entered.
#include <iostream>
using namespace std;
int main() {
int numbers[5];
cout << "Enter 5 numbers: ";
// Store 5 number entered by user in an array
for (int i = 0; i < 5; i++) {
cin >> numbers[i];
}
// Calculate the sum of numbers
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
cout << "Sum = " << sum << endl;
return 0;
}
Sample interaction:
Enter 5 numbers:
32
45
57
142
22
Sum = 298
While Loop
In addition to the for
loop, C++ has another loop known as the while
loop. The while
loop continually executes a block of statements while a particular condition is true. Its syntax is:
while (condition) {
.. statements (loop body) ..
}
The initialization of the variables used in condition can be done anytime before the while
loop, and the value of the variable can be updated anywhere inside the while
loop.
Here’s a while loop which prints the the odd numbers smaller than 10.
int x = 1;
while (x < 10) {
cout << x << endl;
x += 2;
}
Output:
1
3
5
7
9
Let’s see how above program works.
- First, we give
x
an initial value of1
. - Then, the condition
x < 10
is checked. Currently, the value ofx
is1
, hence the conditionx < 10
is true and the loop body will get executed. - Then, in the loop value, we print the current value of
x
(cout << x << endl;
), this prints1
. Then we add2
tox
(x += 2;
) which updates the current value ofx
to3
. - Since
x < 10
is still true (sincex
is equal to3
), the value3
gets printed, and thenx
is updated to5
. - This continues till
x = 9
. Finally, the value ofx
is updated to11
. Then the condition is checked which is no longer true, and the loop execution stops.
Note: If you don’t update the value of the variable used in the condition statement, then the condition will always be true and you will have an infinite loop. That is, your program will keep running forever! If this happens, do Ctrl-C (on windows) or Cmd-C (on OS X) to kill the program.
Break
Lastly, let’s learn about the break
and continue
statements which give us some more control over what code is executed inside a loop. These statements are written inside the loop body.
If a break
is encountered inside a loop, C++ immediate stops iterating over the loop (it also ignores all the code after the break within the block, if any). Here’s an example:
int a[] = {1, 5, 3, 2, 4, 6};
for (int i = 0; i < 6; i++) {
cout << a[i] << endl;
if (a[i] == 2)
break; // quit the loop when element == 2
cout << 10*a[i] << endl; // when element == 2, this line too won't execute
}
Here’s the code output:
1
10
5
50
3
30
2
Note: 2 gets printed, but 20 does not, since break
happens before that. 4 and 6 don’t get printed at all.
Continue
If a continue
is encountered, C++ ignores the code after the continue
within the block, but “continues” iterating over the rest of the elements. Here’s an example:
int a[] = {1, 5, 3, 2, 4, 6};
for (int i = 0; i < 6; i++) {
cout << a[i] << endl;
if (a[i] <= 2)
continue; // don't execute the rest if element <= 2
cout << 10*a[i] << endl; // when element <= 2, this line too won't execute
}
Here’s the code output:
1
5
50
3
30
2
4
40
6
60
Note: All numbers get printed. However, for 1 and 2, the times 10 values won’t get printed because of the continue
.
Both break
and continue
can be used inside while
-loops as well. Try writing some while loops with break
’s and continue
’s and see what you can do!
Summary
In the last few exercises you learned about:
- arrays – you learnt to declare arrays in C++, how to access its elements, and how to iterate over the elements with the help of a loop.
- multi-dimensional arrays - how to declare, initialize and access elements of an array with 2 or more dimensions
- loops – you learnt two types of loops, the
while
-loop and thefor
-loop - break and continue –
break
can be used to exit the loop, andcontinue
can be used to skip some parts of the loop body
Exciting stuff! Let’s do some coding exercises using what you just learnt!