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;

}
4
  • 6
    Smoking gun: for (int i = 1; i <= 10; i++) Commented Mar 26, 2015 at 1:27
  • 1
    Hint; look at the difference between the for loops. Commented Mar 26, 2015 at 1:27
  • Ahh thanks for the hints, changed the for loop to match the above one. Works now! Thanks. Commented Mar 26, 2015 at 1:35
  • -858993460 = 0xCCCCCCCC which means you've accessed uninitialized memory Commented Aug 18, 2018 at 11:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, rewrote the second for loop to match the one above. Fixed the problems completely. Thanks!
Starting from index 1 is perfectly correct in this case. He accesses [0] before the loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.