C++ Code Example: largest number in an array

This code asks the user to enter a quantity of numbers they want to store in an array. The user’s input is stored in the “quantity” variable.

After that, the code enters a for loop that asks the user to enter numbers and stores each number in an array named “numbers”. The number of iterations of the loop is equal to the quantity of numbers entered by the user.

Once the numbers are stored in the array, the code then defines another variable named “currentNumber” and assigns it the value of the first element of the “numbers” array.

The code then enters another for loop that iterates over the array, comparing each number with the “currentNumber” variable. If the current element of the array is larger than “currentNumber”, “currentNumber” is updated with the current element’s value.

Finally, the code outputs the “currentNumber”, which is the largest number in the array, to the console.

``````#include &lt;iostream&gt;
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 largest number in first array position
for(int i = 1; i < quantity; i++) {
if(currentNumber < numbers[i]) {
currentNumber = numbers[i];
}
}

cout << "Largest number in array is: " << currentNumber << endl;
}``````
Output
``````How many numbers do you want to store in array? (1 - 20)
5