You are on page 1of 6


096 Introduction to C++ January 10, 2011

Massachusetts Institute of Technology John Marrero
Lecture 4 Notes: Arrays and Strings
1 Arrays
So far e ha!e used !aria"les to store !alues in #e#ory for later reuse. $e no e%&lore a
#eans to store multiple !alues together as one unit, the array.
'n array is a fi%ed nu#"er of elements of the sa#e ty&e stored se(uentially in #e#ory.
Therefore, an integer array holds so#e nu#"er of integers, a character array holds so#e
nu#"er of characters, and so on. The si)e of the array is referred to as its dimension. To
declare an array in C++, e rite the folloing*
type arrayName[dimension];
To declare an integer array na#ed arr of four ele#ents, e rite int arr[4];
The ele#ents of an array can "e accessed "y using an index into the array. 'rrays in C++ are
)ero+inde%ed, so the first ele#ent has an inde% of 0. So, to access the third ele#ent in arr, e
rite arr[2]; The !alue returned can then "e used ,ust li-e any other integer.
.i-e nor#al !aria"les, the ele#ents of an array #ust "e initiali)ed "efore they can "e used/
otherise e ill al#ost certainly get une%&ected results in our &rogra#. There are se!eral
ays to initiali)e the array. 0ne ay is to declare the array and then initiali)e so#e or all of
the ele#ents*
int arr[4];
arr[0] = 6;
arr[1] = 0;
arr[2] = 9;
arr[3] = 6;
'nother ay is to initiali)e so#e or all of the !alues at the ti#e of declaration*
int arr[4] = { 6, 0, 9, 6 };
So#eti#es it is #ore con!enient to lea!e out the si)e of the array and let the co#&iler
deter#ine the array1s si)e for us, "ased on ho #any ele#ents e gi!e it*
int arr[] = { 6, 0, 9, 6, 2, 0, 1, 1 };
2ere, the co#&iler ill create an integer array of di#ension 3.
The array can also "e initiali)ed ith !alues that are not -non "eforehand*
1 #include <iostream>
2 usin names!ace std;
4 int main"# {
6 int arr[4];
% cout << &'lease enter 4 inteers(& << endl;
9 *or"int i = 0; i < 4; i++#
10 cin >> arr[i];

cout << &,alues in arra- are no.(&;
*or"int i = 0; i < 4; i++#
cout << & & << arr[i];
cout << endl;
20 }
return 0;
4ote that hen accessing an array the inde% gi!en #ust "e a &ositi!e integer fro# 0 to n+1,
here n is the di#ension of the array. The inde% itself #ay "e directly &ro!ided, deri!ed fro# a
!aria"le, or co#&uted fro# an e%&ression*
'rrays can also "e &assed as argu#ents to functions. $hen declaring the function, si#&ly
s&ecify the array as a &ara#eter, ithout a di#ension. The array can then "e used as nor#al
ithin the function. 5or e%a#&le*
0 #include <iostream>
1 usin names!ace std;
3 int sum"const int arra-[], const int lent/# {
4 lon sum = 0;
$ *or"int i = 0; i < lent/; sum += arra-[i++]#;
6 return sum;
% }
9 int main"# {
10 int arr[] = {1, 2, 3, 4, $, 6, %};
11 cout << 01um( 0 << sum"arr, %# << endl;
12 return 0;
13 }
The function sum ta-es a constant integer array and a constant integer length as its argu#ents
and adds u& lent/ ele#ents in the array. It then returns the su#, and the &rogra# &rints out
1um( 2).
It is i#&ortant to note that arrays are passed by reference and so any changes #ade to the
array ithin the function ill "e o"ser!ed in the calling sco&e.
C++ also su&&orts the creation of #ultidi#ensional arrays, through the addition of #ore than
one set of "rac-ets. Thus, a to+di#ensional array #ay "e created "y the folloing*
type arrayName[dimension1][dimension2];
The array ill ha!e dimension1 % dimension2 ele#ents of the sa#e ty&e and can "e thought of
as an array of arrays. The first inde% indicates hich of dimension1 su"arrays to access, and
then the second inde% accesses one of dimension2 ele#ents ithin that su"array. Initiali)ation
and access thus or- si#ilarly to the one+di#ensional case*
1 #include <iostream>
2 usin names!ace std;
4 int main"# {
$ int t.o2im3rra-[2][4];
6 t.o2im3rra-[0][0] = 6;
% t.o2im3rra-[0][1] = 0;
) t.o2im3rra-[0][2] = 9;

9 t.o2im3rra-[0][3] = 6;
10 t.o2im3rra-[1][0] = 2;
11 t.o2im3rra-[1][1] = 0;
12 t.o2im3rra-[1][2] = 1;
13 t.o2im3rra-[1][3] = 1;
1$ *or"int i = 0; i < 2; i++#
16 *or"int 4 = 0; 4 < 4; 4++#
1% cout << t.o2im3rra-[i][4];
19 cout << endl;
20 return 0;
21 }
The array can also "e initiali)ed at declaration in the folloing ays*
int t.o2im3rra-[2][4] = { 6, 0, 9, 6, 2, 0, 1, 1 };
int t.o2im3rra-[2][4] = { { 6, 0, 9, 6 } , { 2, 0, 1, 1 } };
4ote that di#ensions #ust always "e &ro!ided hen initiali)ing #ultidi#ensional arrays, as it
is otherise i#&ossi"le for the co#&iler to deter#ine hat the intended ele#ent &artitioning
is. 5or the sa#e reason, hen #ultidi#ensional arrays are s&ecified as argu#ents to
functions, all di#ensions "ut the first must "e &ro!ided 6the first di#ension is o&tional7, as in
the folloing*
int a5unction"int arr[][4]# { 6 }
Multidi#ensional arrays are #erely an a"straction for &rogra##ers, as all of the ele#ents in
the array are se(uential in #e#ory. 8eclaring int arr[2][4]; is the sa#e thing as declaring
int arr[)];.
2 Strings
String literals such as &7ello, .orld89 are actually re&resented "y C++ as a se(uence of
characters in #e#ory. In other ords, a string is si#&ly a character array and can "e
#ani&ulated as such.
Consider the folloing &rogra#*
1 #include <iostream>
2 usin names!ace std;
4 int main"# {
$ c/ar /ello.orld[] = { :7:, :e:, :l:, :l:, :o:, :,:, : :,
6 :.:, :o:, :r:, :l:, :d:, :8:, :;0: };
) cout << /ello.orld << endl;
10 return 0;
11 }
This &rogra# &rints 7ello, .orld8 4ote that the character array /ello.orld ends ith a
s&ecial character -non as the null character. This character is used to indicate the end of the
Character arrays can also "e initiali)ed using string literals. In this case, no null character is
needed, as the co#&iler ill auto#atically insert one*
c/ar /ello.orld[] = &7ello, .orld89;

The indi!idual characters in a string can "e #ani&ulated either directly "y the &rogra##er or
"y using s&ecial functions &ro!ided "y the C9C++ li"raries. These can "e included in a &rogra#
through the use of the #include directi!e. 0f &articular note are the folloing*
ccty&e 6cty&e.h7* character handling
cstdio 6stdio.h7* in&ut9out&ut o&erations
cstdli" 6stdli".h7* general utilities
cstring 6string.h7* string #ani&ulation
2ere is an e%a#&le to illustrate the ccty&e li"rary*
1 #include <iostream>
2 #include <cct-!e>
3 usin names!ace std;
$ int main"# {
6 c/ar mess-1trin[] = 0t670<9s6=i1=999a9=1>?<@A0;
) c/ar current = mess-1trin[0];
9 *or"int i = 0; current 8= :;0:; current = mess-1trin[++i]# {
10 i*"isal!/a"current##
11 cout << "c/ar#"isu!!er"current# B"current# ( current#;
12 else i*"is!unct"current##
13 cout << : :;
14 }
16 cout << endl;
1% return 0;
1) }
This e%a#&le uses the isal!/a, isu!!er, is!unct, and functions fro# the ccty&e
li"rary. The is+ functions chec- hether a gi!en character is an al&ha"etic character, an
u&&ercase letter, or a &unctuation character, res&ecti!ely. These functions return a :oolean
!alue of either true or *alse. The function con!erts a gi!en character to loercase.
The for loo& "eginning at line 9 ta-es each successi!e character fro# mess-1trin until it
reaches the null character. 0n each iteration, if the current character is al&ha"etic and
u&&ercase, it is con!erted to loercase and then dis&layed. If it is already loercase it is
si#&ly dis&layed. If the character is a &unctuation #ar-, a s&ace is dis&layed. 'll other
characters are ignored. The resulting out&ut is t/is is a strin. 5or no, ignore the "c/ar#
on line 11/ e ill co!er that in a later lecture.
2ere is an e%a#&le to illustrate the cstring li"rary*
1 #include <iostream>
2 #include <cstrin>
3 usin names!ace std;
$ int main"# {
6 c/ar *rament1[] = 0<:m a s0;
% c/ar *rament2[] = 0trin80;
) c/ar *rament3[20];
9 c/ar *inal1trin[20] = 00;
11 strc!-"*rament3, *rament1#;
12 strcat"*inal1trin, *rament3#;
13 strcat"*inal1trin, *rament2#;
1$ cout << *inal1trin;
16 return 0;
1% }
This e%a#&le creates and initiali)es to strings, *rament1 and *rament2. *rament3 is
declared "ut not initiali)ed. *inal1trin is &artially initiali)ed 6ith ,ust the null character7.
*rament1 is co&ied into *rament3 using strc!-, in effect initiali)ing *rament3 to <:m a s.
strcat is then used to concatenate *rament3 onto *inal1trin 6the function o!errites the
e%isting null character7, there"y gi!ing *inal1trin the sa#e contents as *rament3. Then
strcat is used again to concatenate *rament2 onto *inal1trin. *inal1trin is dis&layed,
gi!ing <:m a strin8.
;ou are encouraged to read the docu#entation on these and any other li"raries of interest to
learn hat they can do and ho to use a &articular function &ro&erly. 60ne source is
MIT OpenCourseWare
6.096 Introduction to C++
January (IAP) 2011
For information about citing these materials or our Terms of Use, visit: