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

Program to find largest and smallest element in C++

program to find largest and smallest element in C++ Here we will discuss how to find the smallest element and largest element from inputted One Dimensional Array Elements. 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.
The solution of this problem is given in C++ programming language.

C++ program to find largest element

Implementation:-

  • Take the size of array from the user
  • Input the array elements from the user
  • Initialize small = large = arr[0]
  • Repeat from i = 1 to size of array
  • if(arr[i] > large)
  • large = arr[i]
  • if(arr[i] < small)
  • small = arr[i]
  • Print the element as smallest and largest

C++ Code:-

#include <iostream>

using namespace std;

//C Program to Find Largest and Smallest Element in an Array

int main()
    {
    int a[50], size, i, large, small;

    cout<<"Enter the size of the array: ";
    cin>>size;

    cout<<"Enter the"<<size<<"elements of the array:\n";
    for(i = 0; i < size; i++)
    cin>>a[i];

    large = a[0];
    for(i = 1; i < size; i++)
    {
        if(large < a[i])   // if larger value is encountered
        {
            large = a[i]; // update the value of large
        }
    }
    cout<<"The largest element is: "<<large;

    small = a[0];
    for(i = 1; i < size; i++) { 
        if(small>a[i])   // if smaller value is encountered
        {
            small = a[i];   // update the value of small
        }
    }
    cout<<"\n The smallest element is: %d"<<small;
    return 0;
    }

Output:

Enter the size of the array: 6
Enter the 6 elements of the array:
9
32
14
75
100
55
The largest element is: 100
The smallest element is: 9