Arrays


Array consists of a set of variables of the same data type. Each variable of an array is called its element. Each of the elements of an array are accessed using subscript numbers (or index numbers).

The difference between array and structure is that array consists of a set of variables having the same data type. A structure, on the other hand, can consist of different data types. You'll learn about structures later on. 

As usual, the first step if you want to use an array is declaration.


Declaration of an Array :

data type          variable name [size of array]  ;


Example :

int marks[5];

This means that you have declared an array of integer type. The variable name used is marks and size of array is 5. Hence you have actually declared five integer elements namely : marks[0] , marks[1] , marks[2] , marks[3] and marks[4].

You may have a question at this point : What about marks[5]?

The computer counts from zero onwards. The size of the array we declared is 5. SO if you start counting from zero then the fifth element if four not five. Always keep this in mind : Start counting from zero.


Accessing a particular element :

Accessing an element is easy. Suppose you want to give a value to one of the elements. For example :

marks[0] = 56;

marks[4] = 90;

As simple as that. Just type the variable name followed by the element number within the square brackets.


Initializing an Array :

Suppose you want to intialize the array element values at the beginning itself then do this:

int marks[5] = { 56, 75, 80, 59, 90};

This is initialization at the time of declaration itself. This statement tells the compiler that the value of the first element of the array (or marks[0] ) is 56, the second element ( marks[1] ) is 75 and so on...


The next section is the Projects Section 2

or you could go back to Contents


Copyright © 2002 Sethu Subramanian All rights reserved.