
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Here, first created the function named findLargestGap, where initialized max and min with arr[0].
- 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.
- At last, returned the result max - min.
- In int main(), array arr[ ] is initialized with values and function findLargestGap is called with array and its size 8 as an argument.
Advertisements