Adsense 728 * 15

Search

Custom Search

Program to Delete an Element from an Array - C, C++ Question

Write a C, C++ program to delete an element from an array.  Given an array, Write a code to delete an element from a position input by a user.

To solve this problem, let's first understand what is the input parameter and what's our approach to solve this problem.

In this program, we take an array and position of an element to delete.


Delete Duplicate element in an Array.

Reverse an Array using Recursion.


C++ Program to Delete an Element form an Array



#include <iostream>
using namespace std;

int main() {
 
   
   int a[100], size, pos, i, count = 0;

   cout << "Enter the size of an array \n";
   cin  >> size;
   
   cout << "Enter the value in an array \n";
   
   // Take an input array
   for (i = 0; i < size; i++) {
    cin >> a[i];
   }
   
   //Input position where we delete an element 
   cout << "Enter the position \n";
   cin  >> pos;

  // Traverse till the position of an element
  while(count != pos)   
    count++;

  // Shift by one element
  while(count < size) {
 
     a[count] = a[count+1];
     count++;
   }

   // Reduce the size of an array
   size--;            

  // Print an array after deleting an element
  for(i = 0; i < size; i++) {
   
    cout<<"   "<<a[i];
    
  }

  return 0;
}


Output : 

Enter the size of an array  - 5

Enter the value in an array

2     4     6     1      2

Enter the position    -   2

 2    4   1    2



C Program to Delete an Element from an Array

 #include <stdio.h>

int main() {
 
    /* Let's say you have an array. */
 
    int arr[]={3,1,6,7,2,9,8};
 
   /* You want to delete element on 2nd index which is 6. */
 
   int delindex = 2;
 
   /* Array size. */
 
   int size = 7;
 
   int i;
 
   for(i = delindex; i < size-1; i++){
  
      arr[i]=arr[i+1];
   }
 
 
   /* After deletion the array is. */
 
   for(i=0;i<size-1;i++){
  
          printf("%d ",arr[i]);
    }
    return 0;
}




Output:

3   1   7    2    9     8


Programming questions on Strings

Programming questions on Recursion

Programming questions on Array

Programming questions on Linked List

No comments:

Post a Comment