Algorithm formation in c language

Question:

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;
}
Asked By: anshul raj

||

Answers:

C typically outperforms Python (for obvious reasons). But as Python is a high-level language it’s far more concise. For example:

while value := input('Enter some numbers separated by space: '):
    if 2 in (the_list := list(map(int, value.split()))):
        the_list = the_list[1:] + [0]
    print(the_list)

Console:

Enter some numbers separated by space: 3 4 2 9
[4, 2, 9, 0]
Enter some numbers separated by space: 3 4 9 2
[4, 9, 2, 0]
Enter some numbers separated by space: 2 3 4 5
[3, 4, 5, 0]
Enter some numbers separated by space: 1 3 5 7 9
[1, 3, 5, 7, 9]
Answered By: DarkKnight

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

Answered By: Mostafa_Hegazy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.