Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to find the second largest elements in an array in C++

1 Answer

0 votes
#include <iostream>
#include <climits>

int findSecondLargest(int arr[], int len) {
    int max, secondlargest;

    max = secondlargest = INT_MIN;
    
    for (int i = 0; i < len; i++) {
        if(arr[i] > max) {
            secondlargest = max;
            max = arr[i];
        }
        else if(arr[i] > secondlargest && arr[i] < max) {
            secondlargest = arr[i];
        }
    }
    
    return secondlargest;
}

int main() {
    int arr[] = {42, 7, 93, 58, 29, 61, 17, 84, 36, 75}; 
    int len = sizeof(arr) / sizeof(int);

    int secondlargest = findSecondLargest(arr, len);

    std::cout << "The second largest number is " << secondlargest << std::endl;
}

 
/*
run:
 
The second largest number is: 84
 
*/

 



answered Jan 18, 2021 by avibootz
edited Jan 19, 2025 by avibootz

Related questions

2 answers 165 views
1 answer 155 views
3 answers 231 views
1 answer 91 views
2 answers 151 views
...