Find the difference between the smallest and largest element of an array.

 

A C++ Program to Find the Difference between the Smallest and Largest Element of an Array

        This is most common question in placement tests and technical interviews. In this program the size of the array an array will be provided by user and based on these inputs we need to find the difference between the smallest and largest element of an array.

The solution is provided in below parts.
  1.  Logic of Code
  2.  C++ code 



Find the difference between smallest & largest element of an array.

Input : 

5
10 11 7 12 14

Output :

7

Explanation :

Largest Element   : 14
Smallest Element : 7

Difference = 14 - 7 = 7

Hence the difference between smallest & largest element is 7.


LOGIC :

  •  Input Size of Array
  •  Input Array 
  •  Find the max element
  •  Find the min element
  •  Find the difference ( max - min )
  •  Print the difference

CODE :


 #include <bits/stdc++.h> using namespace std; int difference(int n, int arr[]){ int max = arr[0]; int min = arr[0]; for(int i=1;i<n;i++){ if(arr[i]>max) max = arr[i]; if(arr[i]<min) min = arr[i]; } return(max-min); } int main() { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } cout<<difference(n,arr)<<endl; }


***


!! SUBSCRIBE FOR MORE CODES & VIDEOS !!

Post a Comment

0 Comments