Working with C++ Arrays-min

Arrays in C++ are one of the most important user-defined data types in C++. They can be used to store a large amount of data of the same data type sequentially. C++ also supports N-Dimensional arrays that can be used for problem-solving in scientific computing.

For example, we can use the 2-Dimensional array of C++ to create a matrix, and they have wide usage in NLP, Machine Learning, and Artificial Intelligence. If you want to know more about the basics of c++ arrays, you can follow our step-by-step beginner guide on arrays in C++.

In this tutorial, you will learn how we can insert, delete, traverse, search, and update elements in C++ arrays. To follow this tutorial, it is recommended to download and install a C++ compiler on your computer and run the code on your own computer to better understand it.

Traversing elements of an Array

Traversing an array means displaying all the elements of the array by accessing each element one by one. To traverse an array in C++, we need to use a loop to iterate over each element of the array and use the cout<< operator to display each element of the array to the console. The below program shows a practical demonstration of performing this operation.

// including the iostream file
#include <iostream>
using namespace std;
int main()
{
    int arr[] = {10, 20, 30, 40, 50, 100}; //creating the array
    int n = 6;                             // Length of array
    int i;
    for (i = 0; i < n; i++)
    {
        cout << arr[i] << endl; //displaying each element of the array
    }
    return 0;
}

In the above code, we first include the iostream header file in our code required to use the cout operator. After that, we declare the namespace to be used std. Inside the main function, we created an array with the name arr and initialized it by passing some integers. Finally, we use the for loop of C++ to iterate from 0 to the length of the array and use the cout operator inside the loop to display each element of the array to the console one by one. On running the above code, we will get the output as shown in the below image.

C++ program to traverse the elements of an array
C++ program to traverse the elements of an array

Inserting element in an Array

Inserting an element in an array is an important operation for an array. Our program must be able to insert an element at a given index in an array. To perform this operation, we will shift all the elements (starting from the given index) to the right side in one place and then insert the element at the given position using the assignment operator. See the below code for a practical demonstration of this method.

// Including the iostream header file
#include <iostream>
using namespace std;
int main()
{
    int arr[] = {10, 20, 30, 50, 60, 70, 80, 90, 100};
    int num = 40;                         // element which we want to insert
    int pos = 4;                          // where we need to insert
    int size = sizeof(arr) / sizeof(int); // Length of the array
    int i;
    for (i = size; i >= pos; i--)
    {
        arr[i] = arr[i - 1]; //shifting the elements to right side by one place
    }
    arr[pos - 1] = num; //inserting the element at the required position
    // Displaying the array
    for (i = 0; i <= size; i++)
    {
        cout << arr[i] << endl;
    }
    return 0;
}
/* END OF THE PROGRAM */

In the above code, first, we include the header files and other basic codes. Then, in the main function, we have created an array containing some integers. Next, we create two variables for storing the element we want to insert and the position where to insert, respectively. Then we calculate the array’s length by dividing the size of the array(in byte) by the size of the integer(in byte).

After that, we use the for loop to shift each element towards the right by one position starting from the position where we need to insert the element. Thus, the position we need to start the element will be empty or contain some garbage value. Next, we insert the element at the required position. Finally, we use the traverse method that we learned above to display the array elements. On running the above code, we will get the output as shown in the below image.

C++ program to insert an element at a given position in an array
C++ program to insert an element at a given position in an array

Updating element in an Array

Updating an element in a C++ array is very simple. We need to take the position and value we want to update and then insert the value at the index of that position, replacing the previous value. See the below code for illustration.

// Including the iostream header file
#include <iostream>
using namespace std;
int main()
{
    int arr[] = {10, 20, 30, 50, 50, 60, 70, 80, 90, 100};
    int num = 40;                         // element which we want to insert
    int pos = 4;                          // where we need to insert
    int size = sizeof(arr) / sizeof(int); // Length of the array
    int i;
    arr[pos - 1] = num; //updating the element of the required position
    // Displaying the array
    for (i = 0; i < size; i++)
    {
        cout << arr[i] << endl;
    }
    return 0;
}
/* END OF THE PROGRAM */

In the above code, we first include the required header files and the basic code of C++ programs. Inside the main() function, we created an array containing some integers in which we want to update an element. We created two variables viz. num and pos containing the numbers that we want to insert and the position where to insert. Next, we calculate the length of the array by dividing the size of the array(in bytes) by the size of the integer(in bytes). Then, we use the array indexing method to access the array memory location and insert the element at the required position using the assignment operator. We use the array traversing method that we had discussed earlier to display all the elements of the array. On running the above code, we will get the output as shown in the below image.

C++ program to update the value of a given position of an array
C++ program to update the value of a given position of an array

Searching element in an Array

We can search for an element in an array by using the for loop and if statement. To achieve this, we need to loop over the array elements and compare it with the required element using the if statement. The below code shows a practical demonstration of this method.

// Including the iostream header file
#include <iostream>
using namespace std;
int main()
{
    int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
    int num = 40;                         // element which we want to search
    int size = sizeof(arr) / sizeof(int); // Length of the array
    int i;
    // Searching the array
    for (i = 0; i < size; i++)
    {
        if (arr[i] == num)
        {
            cout << "[+] The element is present at the position " << i + 1 << endl;
        }
    }
    return 0;
}
/* END OF THE PROGRAM */

In the above code, we first include all the required header files. Then, in the main function, we created an array and a variable containing the number we wanted to search. Next, we calculate the array’s length by dividing the size of the array by the size of an integer. Finally, we use a for loop starting from 0 to the length of the array with the if statement to check whether any of the array elements is equal to the required element and if it is equal, then print its position. On running the above code, we will get the output as shown in the below image.

C++ program to search an element in an array and return its position
C++ program to search an element in an array and return its position

Deleting element from an Array

To delete an element from an array, we need to loop over the array starting from the element we want to delete and move each element of the array present after this element a step forward. The practical illustration of this method is shown in the below code.

// Including the iostream header file
#include <iostream>
using namespace std;
int main()
{
    int arr[] = {10, 20, 30, 50, 60, 70, 80, 90, 100};
    int n = 4;                            // position of the element that we want to delete
    int size = sizeof(arr) / sizeof(int); // Length of the array
    int i;
    for (int i = n - 1; i < size; i++)
    {
        arr[i] = arr[i + 1]; //shifting each element to the left by one place
    }
    // Displaying the array
    for (i = 0; i < size - 1; i++)
    {
        cout << arr[i] << endl;
    }
    return 0;
}

In the above function, we first include the required header files. In the main function, we created an array containing some integers and a variable that will store the position of the number which we want to delete. Next, we calculate the array’s length by dividing the size of the array by the size of an integer. Next, we shift each element of the array to the left, starting from the element present next to the one we want to delete. This will replace the element that we want to delete with the next element, and we will get the required array. Finally, we use the method of traversing an array to display the new array in the console. On running the above code, we will get the output as shown in the below image.

C++ program to delete an element from an array at a given position
C++ program to delete an element from an array at a given position

Conclusion

In this tutorial, we have learned how to perform some basic operations like searching, traversing, inserting, deleting, and updating C++ arrays. You may also want to see our step-by-step guide on creating a char array from a string in C++.

Similar Posts

Leave a Reply

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