Largest Gap in an Array in C++



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

Approach

Let's look at the approach we will follow to solve this problem.

  • Firstly, we will initialize the array.
  • Then we will find or search for the max and min elements in the array.
  • And will return max - min.

Example

Here is the following code for finding the largest gap in an array in C++.

#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

Explanation

  1. Here, first created the function named findLargestGap, where initialized max and min with arr[0].
  2. Then, created a loop for finding max and min, where the loop iterates through each element of the array arr[i], and storing max and min accordingly.
  3. At last, returned the result max - min.
  4. In int main(), array arr[ ] is initialized with values and function findLargestGap is called with array and its size 8 as an argument. 
Updated on: 2024-12-03T21:59:29+05:30

267 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements