Arrays in C

Imagine that you have to store and later retrieve the unique ID of all of the registered voters in your city. Yes, you can create and name hundreds of thousands of distinct variable names to store the information. However, that would scatter hundreds of thousands of names all over memory. In addition, there is a good probability that same operation needs to be performed on every variable. Let us assume that these variables are all populated with UID and we need to display them. In C language, we have to use printf() statement on every individual variable. Considering 100 voters and variables names as number0, number1, number2…number99 to store 100 UIDs, then the code to display them will be as follows:

printf(“Voter 1 has UID %d”, number0);
printf(“Voter 2 has UID %d”, number1);
printf(“Voter 3 has UID %d”, number2);
printf(“Voter 100 has UID %d”, number99);

It is obvious that we are simply performing same operation on a set of different data. This means it could be performed more efficiently by using a loop and an Array. Instead of declaring individual variables, such as number0, number1,…number99, we can declare one array variable such as numbers and use numbers[0], numbers[1],…numbers[99] to represent individual variables. So, using arrays the program can rewritten as follows:

int i;
for (i=0; i< 100; i++)
printf(“Voter %d has UID %d”,
i+1, number[i]);

An array has the property that items stored in it are stored contiguously and can be accessed randomly (by position or index). They are simple, fast and can be used as the basis for more advanced data structures. Almost all programming languages support the concept of Arrays.