This blog is under construction

Saturday 27 July 2013

C program to find the minimum difference between two elements in an array

Write a C program to find the minimum difference between two elements in an array.


  #include <stdio.h>
  #define MAX 256

  int main() {
        int i, j, n, temp, max[3] = {0}, data[MAX];

        /* get number of array entries from the user */
        printf("Enter the number of array entries:");
        scanf("%d", &n);

        /* get the array entries from the user */
        printf("Enter your array entries:\n");
        for (i = 0; i < n; i++) {
                printf("Data[%d]: ", i);
                scanf("%d", &data[i]);
        }

        /* finding the difference between first 2 elements in an array */
        if (n > 1) {
                temp = data[0] - data[1];
                max[0] = (temp < 0)?(temp * (-1)) : temp;
                max[1] = 0;
                max[2] = 1;
        }

        /* find the min difference b/w two elements in an array */
        for (i = 0; i < n - 1; i++) {
                for (j = i + 1; j < n; j++) {
                        temp = data[i] - data[j];
                        temp = (temp < 0)?(temp * (-1)) : temp;
                        if (max[0] > temp) {
                                max[0]  = temp;
                                max[1] = i;
                                max[2] = j;
                        }
                }
        }

        /* print the result */
        printf("Minimum difference b/w two elements "
                        "in the given array is %d\n", max[0]);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of array entries:5
  Enter your array entries:
  Data[0]: 10
  Data[1]: 20
  Data[2]: 30
  Data[3]: 40
  Data[4]: 100
  Minimum difference b/w two elements in the given array is 10


No comments:

Post a Comment