This is a Cpp Program which finds the maximum difference all the elements in an array.
Here first we find the largest element in the array and store the result and then find the smallest element in the array and store the result .
Now substract the largest element with the smallest element , this gives us the maximum difference in an array.
PROGRAM :
OUTPUT :
Here first we find the largest element in the array and store the result and then find the smallest element in the array and store the result .
Now substract the largest element with the smallest element , this gives us the maximum difference in an array.
PROGRAM :
#include <iostream> using namespace std; int main() { int i,n,l,s; cout << "\nEnter the no of elements: \t"; cin >> n; int a[n],dup[n]; for(i=0;i<n;i++) { cout << "\nEnter Element " << i+1 << ": \t"; cin >> a[i]; dup[i]=a[i]; //storing the copy of of array[] } for(i=0;i<n;i++) //checking for largest { if(a[0]<a[i]) a[0]=a[i]; } l=a[0]; //storing largest num cout <<"\n\nThe largest among the "<< n <<" numbers is "<<a[0]; for(i=0;i<n;i++) //checking for smallest { if(dup[0]>dup[i]) //we used duplicate because original array[] has changed dup[0]=dup[i]; } s=dup[0]; //storing smallest cout << "\nThe smallest among the "<< n <<" numbers is "<< dup[0]; cout<<"\n\nThe maximum difference among numbers is "<< l-s; return 0; }
OUTPUT :
Cpp - Maximum difference between the elements in an array |
No comments:
Post a Comment