c code to find minimum distance between two numbers

  • c
  • write a c code to find minimum distance between two numbers

    Given an unsorted dynamic array arr and two numbers x and y, find the minimum distance between x and y in arr. The array might also contain duplicates. You may assume that both x and y are different and present in arr. Input: arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3}, x = 3, y = 6

    Code

    #include <stdio.h> #include <stdlib.h> int search(int *arr,int n,int y){ for (int i = 0; i < n; i++) { if (arr[i] == y) { return i; } } } int main() { int n, x, y, a, b; printf("enter the array size\n"); scanf("%d", &n); int *arr = (int *)malloc(n * sizeof(int)); printf("enter the elements\n"); for (int i = 0; i < n; i++) { scanf("%d",&arr[i]); } printf("enter the two numbers to find distance between them\n"); scanf("%d%d", &x, &y); a=search(arr,n,x); b=search(arr,n,y); printf("elements %d and %d\n",x,y); if(b>a){ printf("minimum distace between then is : %d",b-a); } else{ printf("minimum distace between then is : %d",a-b); } return 0; }