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 number in int array with C

1 Answer

0 votes
#include <stdio.h>
#include <limits.h>

int findSecondLargest(int arr[], int size) {
    int first, second;
    
    first = second = INT_MIN;

    for (int i = 0; i < size; i++) {
        if (arr[i] > first) {
            second = first;
            first = arr[i];
        } else if (arr[i] > second && arr[i] != first) {
            second = arr[i];
        }
    }

    return (second == INT_MIN) ? -1 : second; 
}

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

    if (secondLargest == -1) {
        printf("There is no second largest element\n");
    } else {
        printf("The second largest element is %d\n", secondLargest);
    }

    return 0;
}


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

 



answered May 2, 2017 by avibootz
edited Jan 19, 2025 by avibootz

Related questions

1 answer 82 views
2 answers 164 views
1 answer 97 views
1 answer 127 views
1 answer 144 views
1 answer 151 views
...