Search code examples
arrayscalgorithmswap

Algorithm formation in c language


SO i am trying to make a algo that shift element in array when ever 2 is found in array

input 3 4 2 9, output 4 2 9 0 this output is needed , I have tried some sort of code but quite confused cause it either copys or it delete the element , output is 3 4 0 9 or anything like that

int main() {
    int a[4], i, j;
    
    for (i = 0; i < 4; i++) {
        printf("Enter element: ");
        scanf("%d", &a[i]);
    }
    
    void dele() {
        for (i = 0; i < 4; i++) {
            printf("%d",i);
            if (a[i] == 2) {
                printf("Ds");
                for (j = i; j > 0; j--) {
                    printf("DSasdw");
                    a[j+1] = a[j-1];
                    printf("%dww",a[j-1]);
                }
                a[3] = NULL;
                break;
            }
        }
    }
    
    dele();
    
    for (i = 0; i < 4; i++) {
        printf("%d ", a[i]);
    }
    
    return 0;
}

Solution

  • I think this code will do what you want, from my understanding:

    void shift_array(int arr[], int size)
    {
      for (int i = 0; i < size; i++) {
        if (arr[i] == 2) {
          for (int j = 0; j < size - 1; j++) {
            arr[j] = arr[j + 1];
          }
          arr[size - 1] = 0;
          i--;
          size--;
        }
      }
    }
    
    int main()
    {
      int num_elements = 5;
      int a[num_elements], i;
      for (i = 0; i < num_elements; i++) {
        printf("Enter element: ");
        scanf("%d", &a[i]);
      }
    
      shift_array(a, num_elements);
    
      for (i = 0; i < num_elements; i++) {
        printf(" %d ", a[i]);
      }
      return 0;
    }
    

    This function loops through the array until it finds a 2, then the inner loop shifts it to the left by 1 place and make the last element = 0, then we decrease the counter and the size in order to check the newly shifted element until we finish the whole array.

    enter image description here