We have learned the basic data type and we can use that to define any variable, the defined variable will then carry and manage a copy of data of that given type. For example,

int ijk;

 That will define a variable ‘ijk’ of type ‘int’, we can assign any integer to ‘ijk’ any time, ‘ijk’ will then carry that integer from that point on.

Sometime we need to work on more than one instance of data, and they all have the same type. For example, let’s say we design a game that can support up to 50 players, we need to record the score for each player. We could define 50 variables like the following,

int score1, score2, … score50;

That may work,  but has at least two obvious issues, we have to separately operate on each different variable, and it becomes not manageable if we need to support 5000 players.

C language has a data structure defined to handle that,

array: a data structure that can store a fixed number of elements of the same type

 An array can be defined like the following,

<type> array-name [ number-of-elements ];

For example,

int scores[5000];

This defines an array called ‘scores’ that has 5000 elements of integers. Each element of the array can be accessed by its index, starting from zero, for example,

scores[0] is the very first element, and scores[4999] is the last element.

With array, we can easily display all the scores using a loop,

It is very important to note that,

  • array index starts from 0, not 1
  • you can never write beyond the array length, for example, the following will create a serious error and cause the program to crash,

scores[5000] = 123;

An array can be defined initialized or uninitialized, for example, the above scores array is defined uninitialized, we did not give an initial value to each element. We can also give array initial values at definition,

int xyz[5] = {1, 2, 3, 4, 5};

This will define an array of 5 integers, with xyz[0] of value 1, xyz[1] of value 2 and so on.

Array index has to be an integer of value greater than or equal to zero, thus xyz[-1] is incorrect, since there is not element of array that has an index value of -1.

That’s all for Array, with one exception, we haven’t talked about how to pass array around, as a function parameter or return value, which we will learn later on. For now, it is good enough for us to just use array directly …

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">