How To Delete An Element In Array C++?

Pv

Hey, This is a C++ Array tutorial in which we will delete an element from the array.

Full Source code at the last.

Start with the main function. -

#include <iostream>
using namespace std;
int main()
{

Now, we have to declare 2 integer-type variables. -

int array[10];
int etd;



We have to take the value of each element. For this, we will use For loop. (this will take 10 values from the user) -

cout << "Enter 10 data elements in array: ";
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter Element : ";
cin >> array[i];
cout << endl;
}


Now we will take the element's position, of which, we have to delete the value. (this will take the input of the position of the element.) -

cout << "\nEnter position of element to delete : ";
cin >> etd;
cout << endl;


We have made an array of 10 elements, what if the user enters the position above 10. for this, we will use an if statement to verify that the position is below or equal to 10. -

if (etd > 10)
{
cout << "\n Sorry! The maximum range of the array is only 10 : ";
}


If the user has entered a position that is below 10, the code has to run. for that, we will deploy an else statement. -

else
{



After all this, our main works start from here. The first line within this code block "--etd" decrements the value of a variable named "etd" by 1. This suggests that "etd" is the index of the element that needs to be removed from the array. The "for" loop then starts from the index "etd" and goes up to index 9, which is the last index of the array. It copies the value of the next element in the array to the current element, effectively shifting all the elements to the left by one index. -

--etd;
for (int i = etd; i <= 9; i++)
{
array[i] = array[i + 1];
}



Now we will print the final value of all elements of the array using for loop. -

cout << "\n\nNew data in array: ";
for (int i = 0; i < 9; i++)
{
cout << array[i];
cout << " ";
}
}



Close the code. -

return 0;
}


Full Source code - 

#include <iostream>
using namespace std;
int main()
{

int array[10];
// int no;
int etd;

cout << "Enter 10 data elements in array: ";
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter Element : ";
cin >> array[i];
cout << endl;
}

cout << "\nEnter position of element to delete : ";
cin >> etd;
cout << endl;

if (etd > 10)
{
cout << "\n Sorry! The maximum range of the array is only 10 : ";
}
else
{
--etd;
for (int i = etd; i <= 9; i++)
{
array[i] = array[i + 1];
}

cout << "\n\nNew data in array: ";
for (int i = 0; i < 9; i++)
{
cout << array[i];
cout << " ";
}
}
return 0;
}

Thanks.
Tags

Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*