You are on page 1of 11

More with Arrays

Character arrays and


2-dimensional arrays

2-Dimensional arrays
A one-dimensional array can be initialized
like
int myIntegerArray [ ] = {1,3,5,7,47};
Can you have an array of arrays? YES!
int myInteger2DArray [3][4] =
{{1,2,3,4},{5,6,7,8},{4,3,2,1}};

Differences with 2D arrays


You MUST specify the second dimension.
This one is OK below
int myInteger2DArray [ ][4] =
{{1,2,3,4},{5,6,7,8},{4,3,2,1}};
This one is NOT OK below
int myInteger2DArray [3][ ] =
{{1,2,3,4},{5,6,7,8},{4,3,2,1}};

2D arrays as input to functions


Similar rules apply when using as input to functions.
void my_fun(int myIntArray [ ] [4], int size1, int size2);
NOTE: Arithmetic is NOT defined for arrays. I.e., matrix
operations are not defined. A 2D array is just an array of
values.
Access elements intuitively:
myIntArray[0][2] = 5;

Example
Matrix
double myMatrix [5][5];
for(int i=0;i<5;i++) {
for(int j=0;j<5;j++) {
myMatrix [i][j] = i+j;

Before strings
We had to use character arrays. Strings are
much nicer for most applications, but you may
encounter old code, or need to squeeze every
last flop out of your code, or it may be easier to
work with characters rather than avoid them.
char favoriteLetter = S;
char favoriteWord [ ] = {H, e, l, l, o, \0};
The \0 is the end of array character.
Alternatively, one can write
char favoriteWord [ ] = Hello;

chars are like double and int

We can output them too.


char fullName [ ] = Stephen DeSalvo;
cout<<My full name is <<fullName;
This will print out My full name is Stephen
DeSalvo

chars have a numerical value


The letter S is stored in the computer as
83, according to whats called an ASCII
code. ALL characters are stored this way.
int charValue = S;
cout<<The value of S is <<charValue;
This will output The value of S is 83

Remember Strings?
string fullName = Stephen DeSalvo;
How would you find out where the first space
character is ?
You can extract a string data type using
fullName.substr(0,7), but how do you test an
individual character?
You can try fullName.substr(i,1), or you can
access the characters directly.

Strings store characters


string fullName = Stephen DeSalvo;
fullName[3] is a character data type!
Lets extract my first name;

int counter = 0;
while(fullName[counter] != ) {
counter++;
}

cout<<My first name is <<fullName.substr(0,counter);

You might also like