Answer:
Following are the program in c++ language
#include <iostream> // header file
using namespace std; // namespace
void largest(int a[], int size); // function declaration
int main() // main method
{
int arr[30],n,count1=0; // variable declaration
cout<<" enter the size elements in array:";
cin>>n; // read the input by user
cout<<"enter array elements:";
for(int k=0;k<n;k++) // iterating over the loop
cin>>arr[k]; // read the elements in the array
largest(arr,n); // calling function largest
return 0;
}
void largest(int a[], int n1) // function definition
{
int i, maximum, second,count=0; // variable declaration
if(n1<2) // checkiing the condition
{
cout<<"invalid input"; // print the message
return;
}
else
{
maximum =INT8_MIN; // store the minimum value of an object
second=INT8_MIN; //store the minimum value of an object
for(i = 0;i<n1; i ++) // iterating over the loop
{
if (a[i]>maximum) // comparing the condition
{
second = maximum; // store the maximum value in the second variable
maximum = a[i];
count++; // increment the count
}
else if (a[i] > second && a[i] != maximum)
{
second = a[i];
count++;
}
}
}
if(count<2)
{
cout<<"Maximum value:"<<maximum; // display the maximum value
cout<<" all the value are equal";
}
else
{
cout<<"Maximum value:"<<maximum; // display the maximum value
cout<<"Second largest:"<<second;// display the second maximum value
}
}
Output:
enter the size elements in array:4
enter array elements:5
47
58
8
Maximum value:58 Second largest:47
Explanation:
Following are the description of program
- In this program, we create a function largest which calculated the largest and the second largest element in the array.
- Firstly check the size of elements in the if block. If the size is less then 2 then an invalid messages will be printed on console otherwise the control moves to the else block.
- In the else block it stores the minimum value of an object in a maximum and second variable by using INT8_MIN function. After that iterating the loop and find the largest and second-largest element in the array .
- In this loop, we used the if-else block and find the largest and second-largest element.
- Finally, print the largest and second-largest elements in the array