#include <iostream>
// #include <cstdlib>
// using namespace std;
// int * myIntArray = new int[5]; // ****
int main() {
// int min, max;
constint N = 5;
int myIntArray[N];
// cout << "Enter 5 values: " << endl;
std::cout << "Enter " << N << " values:\n" ;
//for (int i = 0; i < 5; i++)
for( int i = 0 ; i < N ; ++i )
{
std::cout << "Enter value: ";
std::cin >> myIntArray[i];
}
// min = myIntArray[0];
// max = myIntArray[0];
int min = myIntArray[0];
int max = myIntArray[0];
//for (int i = 1; i < 5; i++)
for( int i = 1 ; i < N ; ++i )
{
if (min > myIntArray[i])
{
min = myIntArray[i];
}
elseif (max < myIntArray[i])
{
max = myIntArray[i];
}
}
std::cout << "Maximum number is: " << max << '\n' ; // << endl;
std::cout << "Smallest number is: " << min << '\n' ; // << endl;
// delete[] myIntArray;
// return 0; // return 0 is implicit
}
> i need to use new to allocate space for integers which is what i attempted
Why do you need to use new to allocate space for integers?
The number of elements is known at compile-time. constint N = 5;
In the code that I posted, the text in green are lines commented out; they may be deleted.
1 2
//for (int i = 0; i < 5; i++) // this line is commented out (don't hard-code 5)
for( int i = 0 ; i < N ; ++i ) // replaced with this line (instead, use N)
because my professor told me i need to use new. i think he just wants to see if we know how. (which i don't). and thanks for clarifying that green text :)
#include <iostream>
int main() {
int n ;
std::cout << "number of integers: " ;
std::cin >> n ; // n is not known at compile-time
if( n < 1 ) return 1 ; // return 1 to indicate failure
int* myIntArray = newint [n]; // allocate memory for 'n' integers
std::cout << "Enter " << n << " values:\n" ;
for( int i = 0 ; i < n ; ++i )
{
std::cout << "Enter value: ";
std::cin >> myIntArray[i];
}
int min = myIntArray[0];
int max = myIntArray[0];
for( int i = 1 ; i < n ; ++i )
{
if (min > myIntArray[i])
{
min = myIntArray[i];
}
elseif (max < myIntArray[i])
{
max = myIntArray[i];
}
}
std::cout << "Maximum number is: " << max << '\n' ;
std::cout << "Smallest number is: " << min << '\n' ;
delete[] myIntArray ; // free the allocated memory
}