Add an element to an array in C++ only if the element doesn’t already exists

Hey learners, In this tutorial, let us learn a new concept that is how to add an element to an array if the element doesn’t exist in the array already in C++. let us understand the program in a step-by-step process.

Step 1:

As we know that we need to include the required headerfiles and namespaces at the beginning of any program for smooth execution of the program. Therefore, we are including the iostream header file to use cin and cout which are present in iostream. We are using the namespace std so that we can avoid the naming collisions.

#include <iostream>
using namespace std;

Step 2:

Since we can not modify the size of an array at run time we follow an approach in which we will create another array and add the elements to it including the new element. Now, let us go through the main function.

Add non-existing element only to an array in C++

int main() {
    int arr[5]={1,2,3,4,5};
    int size=5,i,ele;
    cout<<"Enter an element you want to add into the array: ";
    cin>>ele;
    for(i=0;i<size;i++) {
        if(ele==arr[i]) {
            cout<<"Element already present";
            return 0;
        }
    }
    int modifiedArr[size+1];
    for(i=0;i<size;i++) {
        modifiedArr[i]=arr[i];
    }
    modifiedArr[size]=ele;
    cout<<"The elements present in the modified array are: ";
    for(i=0;i<=size;i++) {
        cout <<modifiedArr[i]<<" ";
    }
}

In the main() function, we have declared an array named arr with size 5 and initialized it with 5 elements. We will ask the user to enter an element and then we will check if the element entered by the user already exists. If the element entered by the user already exist, then we will be display as “Element already present” and end the program. If the element entered by the user doesn’t exist in the array then we will create a new array named as modifiedArr with size (size+1) of the previous array and then we add every element present in the previous array to the new array with the help of a for loop and also add the new element to it. Now, we will display all the elements present in the modified array.

OUTPUT:

Test Case: 1
Enter an element you want to add into the array: 4
Element already present
Test Case: 2
Enter an element you want to add into the array: 6
The elements present in the modified array are: 1 2 3 4 5 6

Leave a Reply

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