175k views
2 votes
Write a C++ function, lastLargestIndex that takes as parameters an int array and its size and returns the index of the last occurrence of the largest element in the array. Also, write a program to test your function.This solution contains errors:#includeint largestIndex(int list[], int listSize);int main(){int alpha[20];cout << "The index of the first occurrence of the largest element in the array is " << largestIndex(alpha,20) << endl;return 0;}int largestIndex(int list[], int listSize){int i;int minIndex = 0; //Assuming first element is the largestfor (counter = 1; counter < listSize; counter++)if (list[maxIndex] < list[counter])maxIndex = counter;return maxIndex;}

1 Answer

2 votes

Answer:

#include <iostream>

using namespace std;

int largestIndex(int list[], int listSize);

int main()

{

int alpha[10] = { 3, 6, 2, 6, 4, 1, 0, 5, 4, 2 };

cout << "The index of the last occurrence of the largest element in the array is " << largestIndex(alpha, 10) << endl;

return 0; }

int largestIndex(int list[], int listSize) {

int largestIndex = 0;

for (int counter = 1; counter < listSize; counter++)

if (list[counter] >= list[largestIndex])

largestIndex = counter;

return largestIndex;

}

Step-by-step explanation:

The function keeps track of the index of the largest value and updates it when the same or a larger value is found.

User Maqsood
by
8.1k points