This blog is under construction

Saturday, 27 July 2013

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

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


  #include <stdio.h>
  #define MAX 256

  int main() {
        int i, j, n, diff, max[3] = {0}, array[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", &array[i]);
        }

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

        /* print the result */
        printf("Max difference b/w two elements in the given array:\n");
        printf("Difference between %d and %d is %d\n",
                        array[max[1]], array[max[2]], max[0]);
        return 0;
  }



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


1 comment: