In this C++ tutorial, you shall learn how to write a program to find the smallest number in the given integer array.

C++ Program – Find Smallest Number in Integer Array

To find the smallest of elements in an integer array,

  1. Initialize smallest with first element of array.
  2. For each element in the array:
    1. Compare smallest with this element.
    2. If smallest is greater than this element, then update smallest with the element.
  3. smallest contains the smallest number in given integer array.

We will use C++ Greater-than Operator for comparison.

Examples

1. Find smallest number in the array {2, 4, 6, 8, 0, 1}

In the following example, we take an integer array initialized with some elements, and find the smallest number of the elements of this array.

main.cpp

</>
Copy
#include <iostream>
using namespace std;

int main() {
    int x[] = {2, 4, 6, 8, 0, 1}; //integer array
    int len = sizeof(x) / sizeof(x[0]); //get array length
    
    // find smallest only if there is atleast one element in array
    if ( len > 0 ) {
        int smallest = x[0]; //assume that first element is smallest
        
        for ( int i = 1; i < len; i++ ) {
            if ( smallest > x[i] ) {
                smallest = x[i]; //update smallest
            }
        }
        
        cout << "Smallest : " << smallest << endl;
    } else {
        cout << "No elements in the array." << endl;
    }
}

Output

Smallest : 0
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned how to find the smallest of elements of an integer array, with the help of example C++ programs.