C++ Code Example: smallest number in array

This code takes user input to determine the number of elements to store in an integer array “numbers”. It then prompts the user to input the elements and stores them in the array. The code then loops over the array to find the smallest number and outputs it.

The first line is a preprocessor directive that includes the standard input/output library in the code. The second line specifies the standard namespace to use in the program.

The main function is the starting point of the program. Two integer variables quantity and i are declared, and an integer array numbers with 20 elements is also declared.

This part of the code outputs a prompt to the user asking for the number of elements to store in the numbers array, and then stores the user’s input in the quantity variable.

This for loop prompts the user to input quantity numbers, which are then stored in the numbers array.

In the next line, a variable currentNumber is initialized with the value of the first element of the numbers array. Then, the loop iterates over the numbers array, starting from the second element, and compares each element with currentNumber. If an element is smaller than currentNumber, currentNumber is updated with the value of that element. After the loop, currentNumber will hold the value of the smallest number in the numbers array.

Finally, the code outputs the smallest number stored in the currentNumber variable.

#include <iostream>
using namespace std;

int main () {
    int quantity, i;
    int numbers[20];

    cout << "How many numbers do you want to store in array? (1 - 20) " << endl;
    cin >> quantity;

    // Store numbers in array (user input)
    for(i = 0 ; i < quantity ; i++) {
        cout << "Please enter a number: " << endl;
        cin >> numbers[i];
    }
    
    int currentNumber = numbers[0];

    // loop over array and store smallest number in first array position
    for(int i = 1; i < quantity; i++) {
        if(currentNumber > numbers[i]) {
            currentNumber = numbers[i];
        }
    }

    cout << "Smallest number in array is: " << currentNumber << endl;
}
Output
How many numbers do you want to store in array? (1 - 20) 
5
Please enter a number: 
44
Please enter a number: 
77
Please enter a number: 
22
Please enter a number: 
99
Please enter a number: 
53
Smallest number in array is: 22