Lesson 8: Array basics
This is the eight installment of my lessons, and it is
on arrays. Arrays are essentially a way
to store many values under the same name. You can make
an array out of any data-type,
including structures. For example, you could say
int examplearray[100];
//This declares an array
This would make an integer array with 100 slots, or
places to store values. The only difficult
thing is that it starts off with the first index-number,
that is, the number that you put in
the brackets to access a certain element, is zero, not
one!
Think about arrays like this:
[][][][][][]
Each of the slots is a slot in the array, and
you can put information into each one of them. It is
like a group of variables side by side
almost.
What can you do with this simple knowledge? Lets say you
want to store a string, since C++ has
no built-in datatype for strings, in DOS, you can make
an array of characters.
For example:
char astring[100];
Will allow you to declare a char array of 100 elements,
or slots. Then you could get it from
the user, and if the user types in a long string, it
will all go in the array. The neat thing
is that it is very easy to work with strings in this
way, and there is even a header file
called STRING.H.
I will have a lesson in the future on the functions in
string.h, but for now,
lets concentrate on arrays.
The most useful aspect of arrays is multidimensional
arrays.
For example:
int
twodimensionalarray[8][8];
Think about multidimensional arrays:
[][][][][]
[][][][][]
[][][][][]
[][][][][]
[][][][][]
This is a graphic of what a two-dimensional array looks
like when I visualize it.
declares an array that has two dimensions. Think of it
as a chessboard. You can easily use
this to store information about some kind of game, or
write something like tic-tac-toe. To
access it, all you need are two variables, one that goes
in the first slot, one that goes in
the slot. You can even make a three dimensional array,
though you probably won't need to. In
fact, you could make a four-hundred dimensional array.
It is just is very confusing to visualize.
Now, arrays are basically treated like any other
variable. You can modify one value in it by
putting:
arrayname[arrayindexnumber]=whatever;
You will find lots of useful things to do with arrays,
from store information about certain
things under one name, to making games like tic-tac-toe.
One little tip I have is that you use
for loops to access arrays. It is easy:
#include <iostream.h>
void main()
{
int x, y, anarray[8][8];//declares an array like a
chessboard
for(x=0; x<8; x++)
{
for(y=0; y<8; y++)
{
anarray[x][y]=0;//sets all members to zero once loops is
done
}
}
for(x=0; x<8;x++)
{
for(y=0; y<8; y++)
{
cout<<"anarray["<<x<<"]["<<y<<"]="<<anarray[x][y]<<"
";//you'll see
}
}
}
Here you see that the loops work well because they
increment the variable for you, and you only
need to increment by one. It is simple, and you access
the entire array, would you want to use
while loops?
|