Chinaemerem Obidoo
Chimexis Tech Blog


Chimexis Tech Blog


What exactly do arrays mean in programming?

A Tutorial in C.

Chinaemerem Obidoo's photo
Chinaemerem Obidoo
·Apr 19, 2022·

3 min read

This article is about arrays. It is assumed that the reader is familiar with basic programming concepts such as variables and data types. The code snippets are written in the C language. However, you will grasp it as long as you understand the rudiments of code as stated.

In the C language, arrays are a data structure that allows you to store multiple values of the same data type under the same variable name. The data are stored contiguously, i.e. sequentially or next to each other in memory.

To give a clearer picture, consider the following scenario. You want to store the ages of three friends: Michael, James, and Steph. The traditional thing to do is to store the ages using disparate variable names; perhaps using their respective names as variables, thus:

// Declare variables and assign values
      int Michael = 18;
      int James = 17;
      int Steph = 19;

With the use of arrays, we can store the three ages under a single variable, say age, and then note their positions using an index. See the snippet below:

// Declare a variable age with 3 values 
int age[3];

//Assign values based on index/position
age[0] = 18;
age[1] = 17;
age[2] = 19;

From the above, it can be seen that Michael, James, and Steph have index values of 0, 1, and 2 respectively. The index refers to the position of an item in memory and as a programming convention, the index always begins at 0.

The names can also be stored in an array as shown below:

string names[3];
names[0] = "Michael";
names[1] = "James";
names[2] = "Steph";

Moreover, the above arrays can be rewritten in a shorter way using curly braces that encapsulate all values in a single line.

// For the first array
int age[] = {18, 17, 19};

// For the second array
string names[] = {"Michael", "James", "Steph"};

With the use of curly braces, the number of items in the array need not be specified since the computer knows to infer this from the values entered.

But how do we access any value in an array? Well, this can simply be achieved by using the index. For instance, names[1] returns a value "James" while age[2] returns a value 19.

NOTE: The concept of arrays as used in languages such as Javascript offers a slightly different variation than we have discussed here. Quite remarkably, an array in Javascript can contain values of different data types but the fundamental idea remains the same- you are storing multiple items under the same variable. Furthermore, languages like Python use the idea of arrays even more differently. Data structures like lists, tuples, and sets in Python are simply offshoots of the notion of arrays.

To learn more about arrays in Javascript, check out this MDN article here.

Share this