Arrays in Action

Loop
6 min readNov 22, 2023

--

An array is a collection of homogeneous data items of the same type. Data items are stored in contiguous memory locations. For example, we define an ‘int’ array if you wish to store some integers. If you wish to store a single letter (known character in a programming language) we define a ‘char’ type array and so on.

The two common terms associated with an array are as follows:

  1. Element — The data item or value you store in an array.
  2. Index — The location at which you store a particular element or the location associated with an array element. An array is 0 indexed, meaning the first element of an array or an array starts from the 0th index location.

Note that by location we do not mean the memory address, the index is relative to the array and not to memory.

source

Why do we need an array?

An array is used when we have to store a lot of variables of the same data type. For example, let’s say I need to store the percentages of 80 students. To solve this particular problem, either I have to create the 80 variables of float type or create an array of float types with the size 80.

The second option is best because keeping track of all the 100 different variables is a tedious task. On the other hand, dealing with arrays is simple and easy, all 100 values can be stored in the same array at different indexes (0 to 99).

How to declare and initialize arrays in C?

In the above example, we’ve just declared an array, i.e. we have only created an array but not stored values in it. If you notice the first declaration for storing integer values, you can see that the no. 35 is mentioned within [ ] brackets. It means that the maximum number of elements that can be stored in this num array is 35. Thus, if you try to store the 36th element the compiler will give you an error. If you store say only 20 elements, then in C, the rest of the locations will contain garbage values (some random values). But if you try to add an element in this case there will not be any error thrown because garbage values in C denote that the current locations are empty i.e. you may store any number in that place.

You can also hardcode an array as follows:

Here no need to specify size within [ ] as the array is hardcoded and the compiler will automatically understand the size of an array by the no. of elements within { }, known as array ‘length’ in the programming world.

How to access an element from an array?

Consider the former example of int arr[] = {1, 2, 3, 4, 5}. To access an element from an array, following syntax is used:

Recall that arrays are 0 indexed. So 1 is stored at index position 0, 2 is stored at index position 1 and so on. Hence, arr[0] gives value 1. arr[1] will give value 2 arr[2] will give value 3 etc.

Basic operations on array:-

  1. Traversal: Traversal means accessing each element of an array sequentially.
#include <stdio.h>

int main() {
int a[] = {5, 4, 3, 2, 1};

for (int i = 0; i < 5; i++) {
printf("%d ", a[i]);
}

return 0;
}

//Output would be: 5 4 3 2 1

2. Insertion: Insert or store a value/ a new value in an array or at a particular index. We can insert an element in an array at a specific position. We can achieve this only when the array has enough capacity. If we want to add an element at a specified index, then the elements after that specified index must get shifted to their adjacent right to make way for a new element.

void insert(int n, int position, int value, int array[]) {
for (int i = n - 1; i >= position - 1; i--) {
// Shifting all the elements rightward to get position space free.
array[i + 1] = array[i];
}

// Assigning the value to its index
array[position - 1] = value;

printf("Resultant array is: \n");
for (int i = 0; i <= n; i++) {
printf("%d ", array[i]);
}
}

/*
This is a function for inserting an element. It takes parameters
as no. of elements (n), position to insert (position), value to be
inserted (value), and the array created by the user (array).
*/

When no position is specified it is best to insert the element at last. That way there is no need to shift elements, you can simply append the element at position n-1 where n is the size of the array.

Also, note that if the no. of elements or size of an array is n, then the last index position of an element in an array will be n-1. This is because index starts from 0 count and size starts from 1 count.

3. Deletion: We can delete an element at a specified position in an array but this will create a void in the given array. We can fix this by shifting all the elements to the right of the deleted element to their adjacent left positions. This is similar to insertion but instead of shifting elements backwards we shift elements forward.

void del(int n, int value, int array[]) {
// Search the position of the element first
int i, flag = 0; // Flag = 0 means assume element is not present.

for (i = 0; i < n; i++) {
if (array[i] == value) {
flag = 1; // Element is present
break;
}
}

if (flag == 0) {
printf("Element not found!");
} else {
for (int j = i; j < n - 1; j++) {
// Shifting all the elements leftwards
array[j] = array[j + 1];
}

printf("Resultant array is: \n");
for (i = 0; i < n - 1; i++) {
printf("%d ", array[i]);
}
}
}

/*
Function accepts size of array, value to be deleted, and the
array respectively
*/

4. Searching: We can perform searching for an element in an array by traversing the array until the element is found. There are two types of searching algorithms — Linear Search and Binary Search.

While linear search takes time complexity of O(n) and works on both sorted and unsorted arrays, Binary Search reduces time complexity to O(log n) but works only on sorted data.

// Write a program to calculate the average of 4 numbers entered by the user.
#include <stdio.h>

int main() {
int avg = 0;
int sum = 0;
int x = 0;

/* Array declaration – length 4 */
int num[4];

/* We are using a for loop to traverse through the array
* while storing the entered values in the array
*/
for (x = 0; x < 4; x++) {
printf("Enter number %d \n", (x + 1));
scanf("%d", &num[x]);
}

for (x = 0; x < 4; x++) {
sum = sum + num[x];
}

avg = sum / 4;
printf("Average of entered numbers is: %d", avg);

return 0;
}

Advantages of an array:-

  1. Any element of an array can be accessed directly by simply specifying the index value of that element within an array.
  2. Arrays are a foundation to implement various other data structures and sorting algorithms
  3. Arrays can be efficiently iterated using any loops, mostly for loops.

Disadvantages of an array:-

  1. Insertion and Deletion in an array is quite tedious as it requires shifting of elements.
  2. Arrays are always stored in contiguous fashion, this means that if in the memory heap one memory slot is available at memory address say 204 but the next memory slot is occupied then the array cannot store the elements.
  3. Array has a fixed size. This means that if the array is exhausted i.e. we wish to store elements beyond the specified size then it cannot be done. Conversely, if the no. of elements stored are less than the specified size, then it leads to the wastage of memory locations.

--

--

Loop

Competitive coding club at Cummins College of Engineering, Pune