Mastering Arrays in C and C++: Unlocking the Power of Data Structures

·

10 min read

Mastering Arrays in C and C++: Unlocking the Power of Data Structures

C and C++ programmers rely on arrays as a fundamental tool for managing sets of elements, providing a reliable and straightforward approach to data storage and retrieval


What is Array in Programing?

An array is a data structure that stores a collection of elements of the same kind. The system accesses the elements by their index, as they are stored in contiguous memory locations.

In this tutorial, I will cover arrays in C and C++. However, it's important to note that arrays also exist in other popular programming languages, such as Java, JavaScript, and Python. In Python, arrays are commonly referred to as lists.

If you have worked with code in C and C++, you may be familiar with the terms "initializing" and "declaring." If you're not familiar with these terms, don't worry. We will explore and understand the meaning of each term clearly and comprehensively.

Declaring: When we declare a variable or data structure, we are simply telling the computer, “Hey, this is the container I will be using to store information”. By declaring the container, we give it a name that we can easily refer to later.

Initializing: Initializing is simply the purpose of assigning a value to a variable or data structure when it is declared.

Let's imagine we have a special box that we want to use for playing with our friends. Instead of leaving the box empty, we decide to make the playtime more exciting by placing a toy inside it. By doing so, we are giving the box a purpose and making it more meaningful. In the context of programming, this act of putting something inside the box corresponds to initializing it, which means assigning it a value or giving it an initial state. Just like adding a toy to the box enhances the play experience, initializing a variable or data structure with a value adds significance and functionality to it in programming.

How to Declare and Initialize an Array

Before declaring an array in C or C++, certain factors need to be taken into consideration.

  1. The first consideration when declaring an array in C or C++ is determining the type of elements we want the array to store, such as integers, characters, or strings.

  2. The second aspect to consider when declaring an array in C or C++ is choosing an appropriate variable name for our array.

  3. The third is that when declaring an array in C or C++, we must determine the number of elements (size) we want our array to have.

  4. The fourth aspect to consider when declaring an array in C or C++ is deciding on the initial value we want to assign to the array, if any.

Similar to declaring variables by specifying their type, such as int for integers or char for characters, when declaring an array, we need to specify the type of elements we intend to store. As mentioned earlier, an array is a collection of elements that are of the same type. If we plan to store numbers in our array, we would use the type int instead of char. This ensures clarity and consistency in our code, allowing us to work with the appropriate data type for our array.

Additionally, it is necessary to specify the size of the array when declaring it. The size of the array determines the number of elements it can accommodate. By specifying the size, we enable the computer to allocate the precise amount of memory required to store the elements. This allocation is based on the specified size and the size of each element within the array. Specifying the size ensures that the array has enough space to hold the desired number of elements efficiently.

In C and C++, the code can compile successfully even if the size of the array is not explicitly specified. In such cases, the compiler can automatically determine the size of the array by examining the number of elements in the initialization list. However, it's important to note that omitting the size of the array without initializing it can potentially result in compilation errors. It is recommended to either specify the size of the array or initialize it with the appropriate number of elements to ensure predictable behavior and avoid potential issues during compilation.

NB: Arrays are initialized with curly{} braces, and their size is put in square [] brackets.

Below is the C/C++ code to declare an array.

#include <iostream>
using namespace std;

int main()
{
    int myArray[5];
    /**
    Declaring an array of type int
    Array size: 5
    Array name: myArray
    */
    return (0);
}

In the above code, we declared an array of type int with the variable name myArray that can hold 5 elements.

Now, let us note that the size of myArray is 5, but the total size of myArray is 20.

Why is the total size 20?

This is because to get the total size of an array, we multiply the size of each element by the number of elements in the array. In this case, we have 5 elements in the array, and each element is of type int. According to our previous knowledge of data types in C/C++, integers have a size of 4 bytes.

The total size of myArray, therefore, becomes 4 * 5 = 20 bytes.

If you quite remember, I mentioned earlier that, in the case where the size of the array is not specified, the compiler automatically deduces the size of the array based on the number of elements initialized.

#include <iostream>
using namespace std;
int main()
{
    int myArray[] = {2, 4, 5, 6};
   //size: 5
    return (0);
}

From the above code, the compiler determines the size of myArray which is 5 based on the number of elements initialized in the list.

Accessing Elements in an Array

Elements in an array are accessed by their position in the list, using an index. The index starts at 0 for the first element and goes up to n-1 for the last element, where n is the number of elements in the array. For instance, if there are 5 elements, the index will range from 0 to 4.

NB: Index refers to the position of the elements in the array and not the size of values initialized in the array. It is also important to note that, trying to access elements outside the index range, which is from 0 to n-1, of an array can lead to errors during compilation.

#include <iostream>
using namespace std;
int main()
{
    int myArray[] = {2, 4, 5, 6, 8};
   //size: 5
   cout <<"First element of the array is: " << myArray[0] << endl;        // printing the first element of the array to stdout.
   cout <<"Second element of the array is: "<< myArray[1] << endl;       // printing the second element of the array to stdout.
   cout <<"Third element of the array is: " << myArray[2] << endl;        // printing the third element of the array to stdout.
   cout <<"Fourth element of the array is: " << myArray[3] << endl;      // printing the fourth element of the array to stdout.
   cout <<"Fifth element of the array is: " << myArray[4] << endl;       // printing the fifth element of the array to stdout.
    return (0);
}

From the above code, it can be seen that each element of the array was accessed and printed to stdout using the index. As earlier mentioned, the index of the first element is always 0, and the index of the last element is always n-1. In this case, we had 5 elements, so from index 0, our last index will be 5 -1 = 4. Therefore, our last index is 4.

How to Modify Elements in an Array

Just as we can access elements in an array, we can also change elements in an array.

To do so, we first have to access the element we want to make modifications to by using its index, and then assign the new value we want to the array by referencing the element we want to change.

Below is C/C++ code on how to do that.

#include <iostream>
using namespace std;

int main()
{
    int myArray[] = {2, 4, 5, 6, 8};
   //size: 5
   cout << "Before modification: " << myArray[0] << endl;  //printing out first element in the array
   myArray[0] = 80; // Reinitialize first element in the array to 80
   cout <<"After modification: " << myArray[0] << endl; //printing out first element in the array
    return (0);
}

From the above code, we can see that we accessed the first element at index 0 which is 2, and modified it to 80.

The output of the code is shown below:

Traversing through an Array

While learning C/C++, one concept that I initially found challenging was traversal. The difficulty arose because I didn't fully grasp the meaning of the word "traverse." In programming, to traverse means to move across or go through something. In the context of arrays or data structures, it refers to accessing and processing each element or node sequentially. Understanding this basic definition of traversal is crucial for effectively working with data and performing operations on it in a systematic manner.

To perform traversal operations on an array, we employ loops. Loops are fundamental constructs that we encounter in our initial introduction to C and C++. Examples of such loops include the for loop, while loop, and do-while loop. These looping structures enable us to iterate through the array elements systematically, allowing us to access and manipulate each element in the array as needed.

Using a loop for traversal significantly simplifies and speeds up the process of accessing, modifying, and performing operations on array elements. It provides a convenient and efficient way to work with each element within the array.

Let's explore an example code snippet that demonstrates how we can utilize a for loop to print the elements of an array by referencing their indices.

#include <iostream>
using namespace std;

int main()
{
    int myArray[] = {2, 4, 5, 6, 8};
   //size: 5
    int i;
    //Using a for loop to iterate through myArray and print out each element and its corresponding index
   for(i = 0; i < 5; i++)
   {
    cout << "The index of: " << myArray[i] << " is " << i << endl;  
   }
    return (0);
}

As can be seen from the above code, a simple for loop was used to traverse through the elements of the array, and each element was printed together with its corresponding indices.

Output is shown below:

Basic operations done on Arrays

Apart from printing and accessing elements in an array, there are various fundamental operations that we can perform on arrays. Some of these operations include:

  • Sorting: This is the process of arranging the elements in an array in a particular order. That is either ascending or descending.

  • Searching: This operation involves iterating through the array to find a specific element in it.

NB: In C/C++, we cannot directly delete or append elements to an array since it is declared as a fixed size and cannot be changed at compile time.

Advantages of Arrays

  1. Arrays are efficient to access.

  2. Arrays can store a large amount of data.

  3. Arrays are easy to use.

Disadvantages of Arrays

  1. Arrays can only store data of the same type.

  2. Arrays can be difficult to resize.

  3. Arrays can be slow to access if they are large.

Real-life Applications of Arrays

  • In a game, an array can be used to store the positions of all the objects on the screen.

  • In a word processing program, an array can be used to store the text of a document.

  • In a spreadsheet program, an array can be used to store the data in a table.

  • In a database program, an array can be used to store the rows of a table.

Conclusion

Arrays are key data structures in C and C++. They store and manipulate collections of elements of the same type efficiently. Arrays have a fixed size and are accessed using indices. They are used in various fields like gaming, word processing, and databases. Understanding arrays is crucial for C and C++ programmers.

Feel free to reach out to me on Twitter at Yaw__Amponsah or via email at for any further inquiries or discussions.