Open In App

How to Find the Range of Numbers in an Array in C++?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The range of numbers in an array means the difference between the maximum value and the minimum value in the given array. In this article, we will learn how to find the range of numbers in an array in C++.

For Example,

Input:
myArray = {5,10,15,30,25};

Output: Range: 25

Range Within an Array in C++

To find the range of numbers in an array, we will have to first traverse the array, find the maximum and minimum element from the given array, and then calculate the range using the below formula:

Range = maxElement – minElement

To find the Minimum and Maximum, we can use the std::min_element() and std::max_element() functions respectively.

C++ Program to Find the Range of Values in an Array

The below example demonstrates how we can find the range of the numbers in an array in C++.

C++




// C++ program to illustrate how to find the range of the
// array
#include <algorithm>
#include <iostream>
  
using namespace std;
  
int main()
{
    int arr[7] = { 10, 2, 8, 1, 6, 4, 7 };
  
    // Find the minimum and maximum element in the array
    int minElement = *min_element(arr, arr + 7);
    int maxElement = *max_element(arr, arr + 7);
  
    // Calculate the range
    int range = maxElement - minElement;
  
    cout << "The range of the array is: " << range << endl;
  
    return 0;
}


Output

The range of the array is: 9

Time Complexity: O(n), where n is the number of elements in the array.
Auxilliary Space: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads