C++ Program to find Largest and Smallest Element in an Array

Largest and Smallest element in an array in C++

 

Here we will discuss how to find the smallest element and largest element in C++ programming language. In this array we traverse elements recursively and encounter the value of smallest element and largest element until the end of the array with the help of concept of C++ and For loop in the code.

Largest and Smallest element in the array in C++

Here, we will discuss the following methods to find the smallest and largest element in the given input array. Method discuss are :

  • Method 1 : Iterative Approach
  • Method 2 : Top-down recursion
  • Method 3 : Bottom up Recursion

Method 1 :

You can check out the following Pages to know about the iterative algorithm to find the smallest element of the array and the largest element of the array.

Largest and Smallest element

Method 1 : Code in C++

Run
#include<bits/stdc++.h>
using namespace std;
int main(){

    int arr[] = {10, 67, 89, 78, 34, 2, 95};
    int n = sizeof(arr)/sizeof(arr[0]);

    int smallest = INT_MAX, largest = INT_MIN;

    for(int i=0; i<n; i++){ if(smallest > arr[i])
         smallest = arr[i];
       if(largest < arr[i])
         largest = arr[i];
    }

   cout<<smallest<<endl<<largest;
}

Output :

2
95

Method 2 :

You can check out the following Pages to know about the top down recursive algorithm to find the smallest element of the array and the largest element of the array.

Method 2 : Code in C++

Run
#include<bits/stdc++.h>
using namespace std;
int min_element(int arr[], int n)
{

   if (n == 1)
     return arr[0];

   return min(arr[n-1], min_element(arr, n-1));
}

int max_element(int arr[], int n){

   if(n==1)
    return arr[0];

   return max(arr[n-1], max_element(arr, n-1));
}

int main(){

  int arr[] = {10, 67, 89, 78, 34, 2, 95};
  int n = sizeof(arr)/sizeof(arr[0]);

  cout<<min_element(arr, n)<<endl<<max_element(arr, n);
}

Output :

2
95

Method 3 :

You can check out the following Pages to know about the bottom up recursive algorithm to find the smallest element of the array and the largest element of the array.

Method 3 : Code in C++

Run
#include<bits/stdc++.h>
using namespace std;

int minimum(int arr[], int i, int end)
{
   int min;

   if(i == end-1)
    return (arr[i] < arr[i + 1]) ? arr[i] : arr[i + 1];

   min = minimum(arr, i + 1, end);

   return (arr[i] < min) ? arr[i] : min; } int maximum(int arr[], int i, int end) { int max; if(i == end-1) return (arr[i] > arr[i + 1]) ? arr[i] : arr[i + 1];

   max = maximum(arr, i + 1, end);

   return (arr[i] > max) ? arr[i] : max;
}
int main(){

   int arr[] = {10, 67, 89, 78, 34, 2, 95};
   int n = sizeof(arr)/sizeof(arr[0]);

   cout<<minimum(arr, 0, n-1)<<endl<<maximum(arr, 0, n-1);
}

Output :

2
95

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription