Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between two elements so that larger element appears after the smaller number in C?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 567
    Comment on it
    #include<stdio.h>
     
    int maxDiff(int a[], int size)
    {     
      int max_diff = a[1] - a[0];
      int i, j;
      for(i = 0; i < size; i++)
      {
        for(j = i+1; j < size; j++)
        {        
          if(a[j] - a[i] > max_diff)   
             max_diff = a[j] - a[i];
        }    
      }          
      return max_diff;
    }    
     
    int main()
    {
      int a[] = {200, 2, 9, 10, 110};
      printf("Maximum difference is %d",  maxDiff(arr, 5));
      getchar();
      return 0;
    }

    Output:

    Maximum difference is 108

    Explanation:

    In above program following procedure is followed:

    • In maxDiff() function difference of first and second element of array is assigned variable max_diff, within the function two loops are used.
    • In outer loop one by one elements of array a[] is traversed.
    • In inner loop  the difference of the traversed element from outer loop with every other element in the array is calculated and compare the difference with the maximum difference calculated till now.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: