0

I am writing a C++ code that lets the user enter 10 values into an array. The program should then display the largest and smallest values stored in the array. My code so far completes these requirements, however, when running the code, no matter which numbers are input, the program returns -858993460 as the smallest number in the array. The largest number however, is returned without any issues. I have rewritten the code from scratch twice now with the same problem. Using Visual Studio to compile. Thanks for the help.

#include <iostream>

using namespace std;

int main()
{
    int numbers[10];
    int smallest = 0;
    int largest  = 0 ;
    int temp = 0;

    for (int i = 0; i < 10; i++)
    {
        cout << "Please enter a number: " << endl;
        cin >> numbers[i];
    }

    smallest = numbers[0];
    largest = numbers[0];


    for (int i = 1; i <= 10; i++)
    {
        temp = numbers[i];
        if (temp < smallest)
        smallest = temp;

        if (temp > largest)
            largest = temp;
    }

    cout << "The largest number is: " << largest << endl;
    cout << "The smallest number is: " << smallest << endl;

}
NewProgrammer
  • 13
  • 1
  • 5

1 Answers1

1

Your loop that calculates the smallest number has i <= 10 instead of i < 10 as its condition. That means that its last iteration will access numbers[10], but the highest valid index in the array is numbers[9]. You're accessing whatever bytes happen to be located after the end of the array in memory, and those bytes apparently represent the number -858993460 when interpreted as an integer.

You're also starting that loop from 1, which is incorrect since the first element of the array is numbers[0]. I'd guess that you're mistakenly thinking that array indexes count from 1 rather than from 0, but your first loop is correct.

Change your first loop to use < instead of <=, and change it to count from 0 instead of 1.

Wyzard
  • 33,849
  • 3
  • 67
  • 87