Arrays are fundamental data structures in programming that allow the storage of multiple elements of the same data type in contiguous memory locations. Manipulation array, such as deleting an element is a common task in programming. In this article we will write a C program to delete an element from array.
Table of Contents
Process to Delete Element from Array
To delete an element from an array, we need to shift the remaining elements to fill the gap left by the deleted element. The process involves identifying the index of the element to be deleted, shifting the remaining elements that come after it, and updating the array size.
C Program to Delete an Element from Array
Let’s write a C program to perfrom deletion of an elemnt from an array.
#include <stdio.h>
void deleteElement(int array[], int *size, int index)
{
for (int i = index; i < *size - 1; i++)
{
array[i] = array[i + 1];
}
(*size)--;
}
void main()
{
int array[] = {34, 56, 13, 35, 67};
int number, index = -1;
int arraysize = sizeof(array) / sizeof(array[0]);
printf("Enter the element for deletion\n");
scanf("%d", &number);
for (int i = 0; i < arraysize; i++)
{
if (array[i] == number)
{
index = i;
break;
}
}
if (index == -1)
{
printf("Element is not present in the array");
return;
}
printf("Orignal array \n");
for (int i = 0; i < arraysize; i++)
{
printf("%d ", array[i]);
}
deleteElement(array, &arraysize, index);
printf("\nUpdated array after deletion\n");
for (int i = 0; i < arraysize; i++)
{
printf("%d ", array[i]);
}
}
Output
- In the above program, the deletElement function is responsible for deleting the element at the specified index. It performs the deletion by shifting elements to fill the gap and updating the array size.
- The main function takes user input for the element to delete, and then it checks if the number exists in the array or not. If a number exists in the array then the main function calls the deleteElement function.
- At the end, the program prints the updated array after deletion.
Happy Coding
4 thoughts on “C Program to Delete an Element from Array”