Home > Software design >  Delete an element in array using recursion in C
Delete an element in array using recursion in C

Time:09-21

So, here's my code:

int *recursDelete(int arr[], int n, int pos, int i){
    if(i<n){
        arr[pos-1]=arr[i 1];
        recursDelete(arr, n, pos 1, i  );
    }
    
    return arr;
}

I'm trying to copy every element from the given position to the left, and then just return the array. I don't get what is going wrong. Also I'm trying to remove the ifrom the parameter, but if I do that and put i=0 inside the function, then i is always gonna be 0.

CodePudding user response:

Did it:

#include <stdio.h>
int  *recursDelete(int arr[], int n, int poz);
int main()
{
    int arr[]={1,2,3,4,5};
    int *p= recursDelete(arr, 5, 3, 0);
    
    for(int i=0;i<=3;i  ){
        printf("%d", *p);
        p  ;
    }

    return 0;
}

int *recursDelete(int arr[], int n, int poz){
    if(n!=0){
        arr[poz-1]=arr[poz];
        n--
        recursDelete(arr, n, poz 1);
    }
    else{
        return arr;
    }
}

Thanks everyone for the tips!

CodePudding user response:

You need to handle the edge cases. Something like this should work:

void deleteElement(int* ar, int pos, int cur, int maxLen)
{
  if (cur < maxLen)
  {
    if ( cur == maxLen - 1 )
    {
      ar[cur] = 0; // last
      return;
    }
    else if ( cur > pos - 1 )
    {
      ar[cur] = ar[cur   1];
    }
    deleteElement(ar, pos,   cur, maxLen);
  }
}

int main()
{
  int ar[5] = { 1,2,3,4,5 };
  int cur = 0;
  deleteElement(ar, 0, cur, 5);
  for (int i = 0; i < 5;   i)
    printf("=", ar[i]);
}
  • Related