Abhinav K
Abhinav K

Reputation: 57

Deleting a number from an array

I am trying to delete a number from an array at a given position.

IN MY CODE: the array has 5 numbers, 3 6 5 2 4 . I want to delete the number at position 2 which is 5. The output after deleting should be 3 6 2 4. but I am getting 3 6 2 2 4 any help?

MY CODE:

#include<stdio.h>
int main(void){
  int n;
  int i;
  int position;
  int a[10];
  printf("Enter how many numbers\n");
  scanf("%d",&n);
  printf("Enter the numbers\n");
  for(i=0;i<n;i++){
    scanf("%d",&a[i]);
  }
  printf("Enter the position of the number you want to delete\n");
  scanf("%d",&position);

  for(i=0;i<n;i++){
    while(i == position){
      a[i] = a[i+1];
      i = i+1;
    }
  }
  printf("Elements after:\n");
  for(i=0;i<n;i++){
    printf("%d ",a[i]);
  }
  return 0;
}

OUTPUT

Upvotes: 2

Views: 412

Answers (2)

shb
shb

Reputation: 6277

Decrement the size of you array n after you are done shifting and also you can achieve this by

 for(i = position; i < n; i++) {
    a[i] = a[i+1];
  }
  
  n--;

Upvotes: 2

Bill Lynch
Bill Lynch

Reputation: 81936

// To delete a number from the array, we need to shift all of the
// further numbers down one spot. Note that we start the loop at the
// index of the entry we wish to delete.
for(i = position; i < n; i++) { 
  a[i] = a[i+1];
}

// Once we've completed the shift, the array is now smaller.
n = n - 1;

Upvotes: 2

Related Questions