Computer Science, asked by udaykiran939, 1 month ago

flowchart for to find second highest number from given n numbers ​

Answers

Answered by sanjay047
1

Explanation:

Find Second largest element in an array

Given an array of integers, our task is to write a program that efficiently finds the second largest element present in the array.

Example:

Input: arr[] = {12, 35, 1, 10, 34, 1}

Output: The second largest element is 34.

Explanation: The largest element of the

array is 35 and the second

largest element is 34

Input: arr[] = {10, 5, 10}

Output: The second largest element is 5.

Explanation: The largest element of

the array is 10 and the second

largest element is 5

Input: arr[] = {10, 10, 10}

Output: The second largest does not exist.

Explanation: Largest element of the array

is 10 there is no second largest element

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

Approach: The idea is to sort the array in descending order and then return the second element which is not equal to the largest element from the sorted array.

// C++ program to find second largest

// element in an array

#include <bits/stdc++.h>

using namespace std;

/* Function to print the second largest elements */

void print2largest(int arr[], int arr_size)

{

int i, first, second;

/* There should be atleast two elements */

if (arr_size < 2) {

printf(" Invalid Input ");

return;

}

// sort the array

sort(arr, arr + arr_size);

// start from second last element

// as the largest element is at last

for (i = arr_size - 2; i >= 0; i--) {

// if the element is not

// equal to largest element

if (arr[i] != arr[arr_size - 1]) {

printf("The second largest element is %d\n", arr[i]);

return;

}

}

printf("There is no second largest element\n");

}

/* Driver program to test above function */

int main()

{

int arr[] = { 12, 35, 1, 10, 34, 1 };

int n = sizeof(arr) / sizeof(arr[0]);

print2largest(arr, n);

return 0;

}

Similar questions