Google News
logo
C++ Program to Find Smallest Element in an Array
In the following example of C++ program to find the smallest element in an array :
Program :
#include <iostream>

int main() {
    const int SIZE = 5;
    int arr[SIZE];
    std::cout << "Enter " << SIZE << " integers: ";
    for (int i = 0; i < SIZE; i++) {
        std::cin >> arr[i];
    }
    int smallest = arr[0];
    for (int i = 1; i < SIZE; i++) {
        if (arr[i] < smallest) {
            smallest = arr[i];
        }
    }
    std::cout << "The smallest element in the array is " << smallest << std::endl;
    return 0;
}
Output :
Enter 5 integers: 12
27
8
31
18
The smallest element in the array is 8
* This program creates an array arr of size SIZE (which is set to 5 in this example), and prompts the user to enter SIZE integers. It then uses a for loop to iterate over each element of the array, and stores the input in the corresponding element.

* The program then initializes a variable smallest to the first element of the array arr[0]. It then uses another for loop to iterate over each element of the array starting from the second element arr[1].

* For each element arr[i], the program checks whether it is smaller than smallest. If it is, the program updates smallest to the new value of arr[i].

* After the loop completes, smallest will contain the smallest element in the array. Finally, the program outputs the smallest element to the console using std::cout.