Thursday, 26 June 2014

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


Here is a C++ program to find the maximum and minimum difference between two elements in an array.


 SOURCE CODE OUTPUT
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
    int a[20],num,min,max=0,num1,num2,num3,num4;
    cout<<"How many elements to be stored (max 20) : ";
    cin>>num;
    cout<<"Enter elements : ";
    for(int i=0;i<num;i++)
       cin>>a[i];
    min=max=abs(a[0]-a[1]);
    num1=num3=a[0];
    num2=num4=a[1];
    for(int i=0;i<num;i++)
    {
        for(int y=i+1;y<num;y++)
        {
            if(max<abs(a[i]-a[y]))
            {
                max=abs(a[i]-a[y]);
                num1=a[i];
                num2=a[y];
            }
            if(min>abs(a[i]-a[y]))
            {
                max=abs(a[i]-a[y]);
                num3=a[i];
                num4=a[y];
            }
        }
    }
    cout<<"Maximum difference between elements "<<num1<<" and "<<num2<<" : "<<max<<endl;
    cout<<"Minimum difference between elements "<<num3<<" and "<<num4<<" : "<<min;
    return 0;
}
Any questions regarding to program please write in comments.

No comments:

Post a Comment