Arrays

One of the problems programmers face is dealing with a large number of the same datatype. An example of this is this web page. If you view the page source you will see that behind the scenes a web page is a bunch of text. In talking about datatypes, I introduced the char datatype which holds 1 character. But this page consists of a few thousand characters. As a programmer, you would not want to have to create a variable for each character in the page. Programming would be a horribly inefficient means of processing a web page.

The solution to this problem in many programming languages is an array. An array is simply a variable which contains space for more than 1 piece of data of a particular datatype.  So, in processing this web page, your browser has created an array of the char datatype (assuming it is written in C). Let’s suppose that the browser needed an array of 20KB characters to hold and process this page. To get the size of the array we would need for 20KB, we do 20 x 1024 = 20,480 Bytes (or characters). To declare a character array of that size we would add the following line of code:

char thePage[20480];

If we wanted to look at the first character in the page we would use this in our program:

thePage[0]
and the last character in the array would be
thePage[20479]

It is important to remember that C uses a zero based index for arrays. The last element of the array is always indexed at 1 less than the size of the array. The next post will be about program control. With it I will do another example program to demonstrate how arrays are used and why they are so useful. Once you start programming, you will find that you frequently use arrays.