Use a variable int max = array[0];
Iterate through the array. If the current item is greater than the one you already have, then update. If you keep track of the index as well, then just do something like std::cout << "Max at index: " << maxIndex << ", value: " << array[maxIndex] << std::endl;
Well, just not altering the order of elements in the array. Sorting the whole thing would take longer than iterating through and just finding the largest value.
If you want to use arrays, the size has to be determined at compile time and cannot be randomly generated. A way around this is to dynamically create the array.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <algorithm>
usingnamespace std;
constint MAXNUM = 10; // I don't like big numbers when I'm debugging
int main()
{
srand( time(0) );
int N = rand() % MAXNUM + 1; cout << "N=" << N << "\n\n"; // random size for array
int *a = newint[N]; // dynamically allocate array
for ( int i = 0; i < N; i++ ) a[i] = rand() % MAXNUM; // fills with random numbers
for ( int i = 0; i < N; i++ ) cout << a[i] << endl; // for checking only
cout << "Maximum is " << *max_element( a, a + N ) << endl; // calculates maximum and outputs it
delete [] a; // tidy up
}
But, with the above code you might as well be writing C code. Also, a range-based for loop is preferred for iterating through a range (hence the name).