### What's wrong with this?

I'm trying to write a program so the user can enter 10 values and then the program will display the largest and smallest value. I haven't gotten to the smallest value yet. I'm just trying to get the largest to work first. Help please?

 ``123456789101112131415161718192021222324252627282930313233343536373839`` ``````#include using namespace std; int main() { const int SIZE = 10; // Constant for array size int values[SIZE]; // Array to hold values // Get the values. for (int index = 0; index < SIZE; index++) { cout << "Enter value " << index + 1 << ": "; cin >> values[index]; } // Declare an array. int numbers[SIZE] = { values[index] }; // Declare a variable to hold the highest value, and // initialize it with the first value in the array. int highest = numbers[0]; // Step trough the rest of teh array, beginning at // element 1. When a value greater than highest is found, // assign that value to highest. for (int index = 1; index < SIZE; index++) { if (number[index] > highest) { highest = numbers[index]; } } // Display the highest value. cout << "The highest value is " << highest << endl; return 0; }``````
I'm surprised to see two separate arrays here. One array will do.

(actually you can solve this problem without using an array at all).
How would I put this into one array?
Well, you use index on several places, so it is better to declare it in the beginning of the program. You don't need the numbers array, just go through the values.

 ``1234567891011121314151617181920212223242526272829303132333435363738`` `````` #include using namespace std; int main() { const int SIZE = 5; // Constant for array size int values[SIZE]; // Array to hold values int index = 0; // Get the values. for (; index < SIZE; index++) { cout << "Enter value " << index + 1 << ": "; cin >> values[index]; } int highest = values[0]; // Step trough the rest of teh array, beginning at // element 1. When a value greater than highest is found, // assign that value to highest. for (int index = 0; index < SIZE; index++) { if (values[index] > highest) { highest = values[index]; } } // Display the highest value. cout << "The highest value is " << highest << endl; return 0; }``````
That makes sense. This is my first class on C++. It's a lot to take in. Thank you for your help!
And without an array:
 ``123456789101112131415161718192021222324252627`` ``````#include #include using namespace std; int main() { const int SIZE = 10; // Constant for size // Get the values. int highest = std::numeric_limits::min(); int n; for (int index = 0; index < SIZE; index++) { cout << "Enter value " << index + 1 << ": "; cin >> n; if (n > highest) highest = n; } // Display the highest value. cout << "The highest value is " << highest << endl; return 0; }``````

The only tricky part is line 11, where `highest` is set to the smallest value possible.
http://www.cplusplus.com/reference/limits/numeric_limits/
Last edited on
Topic archived. No new replies allowed.