101k views
3 votes
Complete the given C program (prob1.cpp) to read an array of integers, print the array, and find the 2nd largest element in the array. A main function in prob1.cpp is given to read in the array. You are to write two functions, printArray() and getElement(), which are called from the main function. printArray() outputs integers with a space in between numbers and a newline at the end. getElement() returns an integer that is the second largest element in the array. You may assume that the integers are unique.

1 Answer

6 votes

Answer:

#include <stdio.h>

int getElement(int arr[], int size) {

int largest2, largest = 0;

for(int i=0; i<size; i++)

{

if(arr[i] > arr[largest])

{

largest = i;

}

}

if(largest != 0)

largest2 = 0;

else

largest2 = size - 1;

for(int i=0; i<size && i != largest ;i++)

{

if(arr[i] > arr[largest2])

largest2 = i;

}

return arr[largest2];

}

printArray(int arr[], int size) {

printf("The array is: ");

for(int i=0; i<size; i++)

{

printf("%d ", arr[i]);

}

printf("\\");

}

int main()

{

int arr[5] = {30, 20, 5, 10, 24};

printArray(arr, 5);

printf("Second largest number is: %d", getElement(arr, 5));

return 0;

}

Step-by-step explanation:

Since you did not provide any code, I wrote it from the scratch. I also added the main function for you to check the result.

printArray function basically prints the element of the array

getElement function:

- Declare the two variables to hold the value for largest and second largest

- Inside the first loop, check if there is any number that is greater than largest, if yes, assign it to largest

- Inside the second for loop, check if there is any number that is greater than largest2, if yes, assign it to largest2 (Be aware that the largest we found in the first loop is excluded)

- Return the second largest

* Notice that we were able to apply this solution since the numbers are unique.

User David Buck
by
5.4k points