Largest gap in an array in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the largest difference between the two elements in the given array.

Let's see the steps to solve the problem.

  • Initialise the array.
  • Find the max and min elements in the array.
  • Return max - min.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findLargestGap(int arr[], int n) {
   int max = arr[0], min = arr[0];
   for (int i = 0; i < n; i++) {
      if (arr[i] > max) {
         max = arr[i];
      }
      if (arr[i] < min) {
         min = arr[i];
      }
   }
   return max - min;
}
int main() {
   int arr[] = {3, 4, 1, 6, 5, 6, 9, 10};
   cout << findLargestGap(arr, 8) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

9

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 09-Apr-2021 13:26:16
Advertisements