int Largest(int ArrayFill[], int x);
int SecondLargest(int ArrayFill[], int y, int z);
int main()
{
const int MAX = 20;
int largest;
int ArrayFill[MAX];
for (int i = 0; i < MAX; i++)
{
cout << "Enter an integer: ";
cin >> ArrayFill[i];
}
cout << "Largest value is: " << Largest(ArrayFill, MAX)<<endl;
largest = Largest(ArrayFill, MAX);
cout << "Second largest value is: " << SecondLargest(ArrayFill, MAX, largest)<<endl;
system("PAUSE");
return 0;
}
int Largest(int ArrayFill[], int x)
{
int largest = ArrayFill[0];
for (int i = 0; i < x; i++)
{
if (ArrayFill[i] > largest)
largest = ArrayFill[i];
return largest;
}
}
int SecondLargest(int ArrayFill[], int y, int z)
{
int slargest = ArrayFill[0];
for (int i = 0; i < y; i++)
{
if (ArrayFill[i] > slargest&&ArrayFill[i] < z)
slargest = ArrayFill[i];
}
What should SecondLargest() do if there are two instances of the largest value? I.e. with an array of 1 2 3 4 4, is the second largest 4 or 3? If it's 4 then your code isn't quite right.
Fixing this is actually easy. Just change Largest() to return the index of the largest value rather than the value itself. Pass the index to SecondLargest and skip that value:
1 2 3 4 5 6 7 8 9 10
int SecondLargest(int array[], int arraySize, int indexOfLargest)
{
int result = (indexOfLargest ? array[0] : array[1]); // gotta deal with indexOfLargest==0
for (int i=0; i<arraySize; ++i) {
if (i != indexOfLargest && array[i] > result) {
result = array[i];
}
}
return result;
}