C

How To Delete an Element From an Array in C

In this tutorial, we are going to see how to delete an element from an array in C. Note: Delete an element from an array does not mean to decrease the size of the array.

For example, consider the following array arr[10] with four elements:

arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40

And suppose you want to delete the value 10 which is in the first position of the array. So we have to move the elements by one cell (position – 1) so that after the deletion, we will have:

arr[0] = 20
arr[1] = 30
arr[2] = 40
100-multiple-choice-questions-in-c-programming100 Multiple Choice Questions In C Programming – Part 1This collection of 100 Multiple Choice Questions and Answers (MCQs) In C Programming : Quizzes & Practice Tests with Answer focuses on “C Programming”.  …Read More
 

How To Delete an Element From an Array in C
#include <stdio.h>
 
int main()
{
   int position, i, nbr;
   int arr[100];
 
   printf("Enter the number of elements in the array: ");
   scanf("%d", &nbr);
 
   printf("Enter the %d elements: ", nbr);
 
   for (i = 0; i < nbr; i++)
      scanf("%d", &arr[i]);
 
   printf("Enter the position where you want to delete the element: ");
   scanf("%d", &position);
 
   if (position >= nbr+1)
      printf("Unable to delete.\n");
   else
   {
      for (i = position - 1; i < nbr - 1; i++)
         arr[i] = arr[i+1];
 
      printf("After deletion, the array = ");
 
      for (i = 0; i < nbr - 1; i++)
         printf("%4d", arr[i]);
   }
 
   return 0;
}

Output:

Enter the number of elements in the array: 3
Enter the 3 elements: 5 3 9
Enter the position where you want to delete the element: 2
After deletion, the array =    5   9

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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