I want to find the min and max value of an array that the user inputs... Can't get it to work. for 2 and 3 index array, it prints out really high numbers, and for arrays with 9 and 10 indices as well....
/*
Write a program that reads from user a sequence of N integers and return min and max values.
*/
#include <iostream>
usingnamespace std;
int main ()
{
int n = 0;
cout<< "How many numbers do you want to input? " << endl;
cin>> n;
int arr[n];
int tempMax = arr[0]; //assigns max value
int tempMin = arr[n]; //assigns min value
cout<< "Input: " << endl;
for(int i = 0; i < n; i++)
{
cin>> arr[i];
if(arr[i] < tempMin)
{
tempMin = arr[i];
}
if(arr[i] > tempMax)
{
tempMax = arr[i];
}
}
cout<< "Min: " << tempMin << endl;
cout<< "Max: " << tempMax << endl;
return 0;
}
First issue is on line 13 where you are creating a variable length array (which are not supported in standard C++, but are provided by GCC as an extension [this is why your code compiled for you]). You should be creating the array like this instead:
1 2 3 4 5 6 7 8 9 10
#include <iostream>
int main()
{
int x;
std::cin >> x;
int* arr = newint[x];
// use arr here, then...
delete[] arr;
}
or even better:
1 2 3 4 5 6 7 8 9
#include <iostream>
#include <memory>
int main()
{
int x;
std::cin >> x;
std::unique_ptr<int[]> arr(newint[x]);
// use arr here
}
On lines 14 and 15, you are initializing those two variables to the contents of whatever was in the first two elements of your newly created array, which could be anything. You can set them to values more fitting for their use like so:
1 2 3 4 5 6 7 8 9 10 11
#include <limits>
int main()
{
// initialize 'min' to the largest number possible
// Any number compared to 'min' for the first time (except the maximum allowed value) should be lower
int min = std::numeric_limits<int>::max();
// initialize 'max' to the smallest number possible
// Any number compared to 'max' for the first time (except the minimum allowed value) should be greater
int max = std::numeric_limits<int>::min();
}