Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

lasrgest two The existing code is trying to call a function printLargestTwo that

ID: 641411 • Letter: L

Question

lasrgest two

The existing code is trying to call a function printLargestTwo that should take in an array of ints and its size and prints the two largest values from the array. Write that function.
Hint: Start by finding just the largest item (you've seen an example of find smallest...). Then modify it to also look for second largest... Each new number you see is either A: the largest (in which case the old largest is now the second largest), B: the new second largest, or C: neither the new largest nor second largest.

#include <iostream>

using namespace std;

//Do not modify anything on or above the line below this
//START_PROVIDED

//YOUR_CODE

//END_PROVIDED
//Do not modify anything on or below the line above this


int main()
{
    int NUM_VALUES; //cheating to make this flexible
    cin >> NUM_VALUES;
    int values[NUM_VALUES];
    //Read in values
    for(int i = 0; i < NUM_VALUES; i++) {
        cin >> values[i];
    }

    printLargestTwo(values, NUM_VALUES);
}

Explanation / Answer

#include <iostream>

using namespace std;

//Do not modify anything on or above the line below this
//START_PROVIDED

//YOUR_CODE
void printLargestTwo(int values[], int size){
   int lind = -1;
   int slind = -1;
   for(int i = 0; i < size; ++i){
       if(lind == -1 || values[lind] < values[i]){
           lind = i;
       }
   }
   for(int i = 0; i < size; ++i){
       if(slind == -1 || values[slind] < values[i]){
           if(i != lind){
               slind = i;
           }
       }
   }
   cout << values[lind] << " " << values[slind] << endl;
}
//END_PROVIDED
//Do not modify anything on or below the line above this


int main()
{
int NUM_VALUES; //cheating to make this flexible
cin >> NUM_VALUES;
int values[NUM_VALUES];
//Read in values
for(int i = 0; i < NUM_VALUES; i++) {
cin >> values[i];
}

printLargestTwo(values, NUM_VALUES);
}