C program to delete an element from an array
This tutorial will show you how to delete an element from an array in C.
Problem description #
We have an array of integers and we want to delete an element from it.
Examples #
Problem Solution #
- Create an array of integers.
- Ask the user to enter the index of the element to be deleted.
- Delete the element from the array.
- Print the array.
Delete element by index #
In this approach, we will use a loop to iterate through the array and delete the element from the array.
Approach #
- Create an array of integers.
- Ask the user to enter the index of the element to be deleted.
- Loop through the array and delete the element from the array.
- Print the array.
Program/Source code #
Explanation #
The program will ask the user to enter the size of the array and then the elements of the array. The program will then ask the user to enter the index of the element to be deleted. The program will then loop through the array and delete the element from the array. The program will then print the array.
Space Complexity #
The space complexity of this program is O(1).
Time Complexity #
The time complexity of this program is O(n).
Output #
Delete element by value #
In this approach, we will use a loop to iterate through the array and delete the element from the array.
Approach #
- Create an array of integers.
- Ask the user to enter the value of the element to be deleted.
- Loop through the array and delete the element from the array.
- Print the array.
Program/Source code #
Explanation #
The program will ask the user to enter the size of the array and then the elements of the array. The program will then ask the user to enter the value of the element to be deleted. The program will then loop through the array and delete the element from the array. The program will then print the array.
Space Complexity #
The space complexity of this program is O(1).
Time Complexity #
The time complexity of this program is O(n).
Output #
Advanced approach #
In this approach we’ll use separate functions to delete elements by index or by value and give back the array after deleting the element.
Approach #
- Create an array of integers.
- Give the user the option to delete an element by index or by value.
- Delete the element from the array.
- Print the array.
Program/Source code #
Methods used #
- delete_element_by_index() — This function will delete the element from the array by index.
- delete_element_by_value() — This function will delete the element from the array by value.
- print_array() — This function will print the array.
Explanation #
The program will ask the user to enter the size of the array and then the elements of the array. The program will then ask the user to enter the index of the element to be deleted. The program will provide a choice between deleting element by value or by index. The program will then call the function delete_element_by_index() to delete the element from the array. The program will then call the function print_array() to print the array. The program will then ask the user to enter the value of the element to be deleted. The program will then call the function delete_element_by_value() to delete the element from the array. The program will then call the function print_array() to print the array.
Удаление элементов из массива
Чтобы удалить элемент
из массива
, необходимо сдвинуть элементы
на один «шаг» влево и уменьшить значение
на 1. Если
, то в этом случае достаточно выполнить
.
Пример 1. Из массива Х удалить минимальный элемент.
double Xmin, x[NMAX];
//ВВод n и массива x
Xmin=x[0]; imin=0; // Определение положения
for (i=1; i<n; i++) // (индекса) минимального
if (x[i]<Xmin) // элемента
for (i=imin; i<n-1; i++) // Удаление элемента
x[i]=x[i+1]; // с индексом imin
n—; // Уменьшение размера массива
//Печать массива x
Если imin = n-1, то второй цикл for не работает (не выполняется условие входа в цикл), но размер массива n уменьшается на 1.
Пример 2. Из массива Х удалить все нулевые элементы.
В программе будем последовательно просматривать элементы массива и, если очередной элемент
, то производим сдвиг подмассива
на один элемент влево, одновременно уменьшая количество элементов
.
//ВВод n и массива x
for (j=i; j<n-1; j++) // Удаление элемента
x[j]=x[j+1]; // с индексом i
n—; // Уменьшение размера массива
//Печать массива x
По поводу программы вариант 1 можно сделать два замечания.
1. При i = n-1, когда анализируется последний элемент массива, параметр j принимает значение n-1, т.е. начальное значение параметра цикла не соответствует условию входа в цикл j<n-1. Оператор for в этом случае не выполняется, т.е. оператор цикла эквивалентен пустому оператору. Следовательно, при
происходит лишь уменьшение значения n, что соответствует алгоритму решения задачи.
2. Предположим, что в массиве X имеются подряд идущие нулевые элементы
и
. При i = k будет удален элемент
, а на его место перемещается элемент
, также равный нулю. Поскольку при новом повторении цикла for параметр цикла принимает очередное значение k+1, то новый нулевой элемент
не будет анализироваться повторно и, как следствие, не будет удален из массива. Поэтому при наличии в массиве подряд идущих нулевых элементов программа варианта 1 работает неправильно.
Для корректного решения поставленной задачи нужно, чтобы программа после удаления нулевого элемента
повторно анализировала этот же элемент и переходила к рассмотрению элемента
лишь при
0. Для этого нужно в программе вместо цикла for использовать цикл while:
Вариант 2 (фрагмент).
//Ввод n и массива x
for (j=i; j<n-1; j++) // Удаление элемента
x[j]=x[j+1]; // с индексом i
n—; // Уменьшение размера массива
//Печать массива x
Тот же эффект можно достичь с помощью оператора for, если просмотр массива выполнять справа налево.
Вариант 3 (фрагмент).
//ВВод n и массива x
for (j=i; j<n-1; j++) // Удаление элемента
x[j]=x[j+1]; // с индексом i
n—; // Уменьшение размера массива
//Печать массива x
Обнаружение нулевого элемента во внешнем цикле и, как следствие, его удаление из массива приводит к перемещению уже обработанных элементов в «хвосте» массива и не влияет ни на количество повторений внешнего цикла, ни на анализ оставшихся элементов.
Рассмотрим еще один вариант программы, предназначенной для удаления нулевых элементов из массива. В этом случае все ненулевые элементы переносятся в начало массива. Для этого в переменную j перед началом цикла заносится -1. Если был найден ненулевой элемент массива, значение увеличивается на 1, и найденный элемент массива переписывается на место j-го элемента, если j!=i. Таким образом, в j находится номер последнего ненулевого элемента, перенесенного в начало массива. После цикла устанавливается новая длина массива n=j+1.
Вариант 4 (фрагмент).
//ВВод n и массива x
//Печать массива x
В 4-м варианте перемещается лишь один элемент массива (и то не в каждом цикле), в то время как в предыдущих вариантах при удалении каждого элемента, кроме последнего, передвигается вся правая часть массива, причем чем ближе удаляемый элемент к началу массива, тем больше элементов перемещается справа налево. Этот способ является наиболее эффективным.
C program to delete an element from an array

C program to delete an element in an array: This program deletes or removes an element from an array. A user will enter the position at which the array element deletion is required. Deleting an element does not affect the size of the array. It also checks whether deletion is possible or not, for example, if an array contains five elements and user wants to delete the element at the sixth position, it isn’t possible.
Remove element from array C program
int main ( )
<
int array [ 100 ] , position , c , n ;
printf ( «Enter number of elements in array \n » ) ;
scanf ( «%d» , & n ) ;
printf ( «Enter %d elements \n » , n ) ;
for ( c = 0 ; c < n ; c ++ )
scanf ( «%d» , & array [ c ] ) ;
printf ( «Enter the location where you wish to delete element \n » ) ;
scanf ( «%d» , & position ) ;
if ( position >= n + 1 )
printf ( «Deletion not possible. \n » ) ;
else
<
for ( c = position — 1 ; c < n — 1 ; c ++ )
array [ c ] = array [ c + 1 ] ;
printf ( «Resultant array: \n » ) ;
for ( c = 0 ; c < n — 1 ; c ++ )
printf ( «%d \n » , array [ c ] ) ;
>
C program to delete element from array output:
You may have observed that we need to shift array elements which are after the element to be deleted, it’s very inefficient if the size of the array is large or we need to remove elements from an array repeatedly. In linked list data structure shifting isn’t required only pointers are adjusted. If frequent deletion is required and the number of elements is large, it’s recommended to use a linked list.
Removing elements from an array in C
What is the best way to remove elements from an array and in the process make the array smaller.
ie: the array is n size, then I take elements out of the array and then the array grows smaller by the amount that I removed it from.
basically I’m treating the array like a deck of cards and once I take a card off the top of the deck it shouldn’t be there anymore.
EDIT: I’m going to drive myself crazy before the end of the day, thanks for all the help I’m trying the value swapping thing but it’s not working right.
![]()
6 Answers 6
There are really two separate issues. The first is keeping the elements of the array in proper order so that there are no «holes» after removing an element. The second is actually resizing the array itself.
Arrays in C are allocated as a fixed number of contiguous elements. There is no way to actually remove the memory used by an individual element in the array but the elements can be shifted to fill the hole made by removing an element. For example:
Statically allocated arrays can not be resized. Dynamically allocated arrays can be resized with realloc(). This will potentially move the entire array to another location in memory, so all pointers to the array or to its elements will have to be updated. For example:
realloc will return a NULL pointer if the requested size is 0, or if there is an error. Otherwise it returns a pointer to the reallocated array. The temporary pointer is used to detect errors when calling realloc because instead of exiting it is also possible to just leave the original array as it was. When realloc fails to reallocate an array it does not alter the original array.
Note that both of these operations will be fairly slow if the array is large or if a lot of elements are removed. There are other data structures like linked lists and hashes that can be used if efficient insertion and deletion is a priority.