Find the smallest and largest number in an array in C++

This is a C++ program to find the smallest and largest number in a given array. It uses a simple comparison method that is applicable in any program. This method uses two variables in which the value of one is very big and another is very small which holds the value of the smallest and greatest number respectively. Let’s see how.

How to find the smallest and largest number in an array in C++

Programming approach

  • Initialize an integer array and store many values in it.
  • Declare variables for storing the smallest and largest values of array.
  • Find minimum and maximum values and store them in proper variables.
  • Print the values on the screen.

C++ Program/Source code

Following C++ program is able to find the smallest and largest number in an array, is written and successfully compiled.

/* C++ program to find smallest and largest number in an array
****comparison method to find the smallest and largest value is utilized**
 change the array values to get corresponding result
 */

#include <iostream>

using namespace std;

int main()
{
    int array[]={56,45,13,4,69,45,123,45,13,18,63,95,64,46,23,43,62,88,65,462};      // array containing 20 valued

    int small=999999;               //variable for smallest value
    int large=0;                    //variable for largest value

    int size=20;                    //array size

    for(int i=0;i<size;i++){
        if(array[i]<small)              // condition for smallest value
            small=array[i];
        if(array[i]>large)             // condition for largest value
            large=array[i];
    }

    cout<<"Array values are "<<endl;
    for(int i=0;i<size;i++)
        cout<<array[i]<<"\t";           //print array
    cout<<endl;

    cout<<"Smallest value is "<<small<<endl;
    cout<<"Largest value is "<<large<<endl;

    return 0;
}

Output

Array values are
56 45 13 4 69 45 123 45 13 18 63 95 64 46 23
43 62 88 65 462
Smallest value is 4
Largest value is 462

Process returned 0 (0x0) execution time : 0.104 s
Press any key to continue.

Program explanation

  1. An array is initialized and many numbers are stored in it randomly.
  2. A variable with a large value is declared for storing the smallest value.
  3. Similarly, a variable with small value (i.e. 0) is declared for largest value.
  4. A for loop is utilize in which all the array values are compared with the above two variables such that the smallest and largest value get stores in respective variables.
  5. Values of the smallest and largest number prints on the screen.

Also read-

Leave a Reply

Your email address will not be published. Required fields are marked *