Open In App

How to Find the Range of Values in a 2D Array in C++?

In C++, 2D arrays are also known as a matrix, and the range of numbers in a 2D array means the maximum and the minimum value in which the numbers lie in the given 2D array. In this article, we will learn how to find the range of numbers in a 2D array in C++.

For Example,



Input: 
my2DArray= {{80, 90, 100},
{40, 50, 60},
{10, 20, 30}};

Output:
The Range of numbers in the 2D array: [10 to 100]

Range of Values in a 2D Array in C++

To find the range of numbers in a 2D array in C++, we need to find the minimum and the maximum elements present in the 2D array. For that, we can use the std::min_element() and the std::max_element() methods provided by the STL library in C++ that returns the pointer to the smallest and largest value in the given range.

C++ Program to Find the Range of Values in a 2D Array in C++

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






// C++ program to find the range of numbers in a 2D array
#include <algorithm>
#include <iostream>
using namespace std;
  
// define the dimensions for the 2D array
#define ROW 3
#define COL 3
  
int main()
{
    // Initialize a 2D array
    int arr[ROW][COL] = { { 80, 90, 100 },
                          { 40, 50, 60 },
                          { 10, 20, 30 } };
  
    // Find the minimum and maximum element of the 2D array
    // to determine the range of numbers
    int min_val
        = *min_element(&arr[0][0], &arr[0][0] + ROW * COL);
    int max_val
        = *max_element(&arr[0][0], &arr[0][0] + ROW * COL);
  
    // Print the range of numbers in the 2D array
    cout << "The Range of numbers in the 2D array: ["
         << min_val << " to " << max_val << "]";
    return 0;
}

Output
The Range of numbers in the 2D array: [10 to 100]

Time Complexity: O(N * M) where N is the number of rows and M is the number of columns.
Auxiliary Space: O(1)

Article Tags :