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,954 questions

51,896 answers

573 users

How to print the N largest numbers in array with C

2 Answers

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

int compare_function(const void* a, const void* b) {
    return (*(int*)b - *(int*)a);
}

void printNLargest(int arr[], int size, int N) {
    qsort(arr, size, sizeof(int), compare_function);

    for (int i = 0; i < N; i++)
        printf("%3d", arr[i]);
}

int main(void) {
    int arr[] = { 50, 99, 20, 100, 76, 33, 87, 40, 81, 80 };
    int size = sizeof(arr) / sizeof(arr[0]);
    int N = 4;

    printNLargest(arr, size, N);

    return 0;
}




/*
run:

100 99 87 81

*/

 



answered May 16, 2022 by avibootz
0 votes
#include <stdio.h>

int getMax(int arr[], int size) {
    int max = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > max)
            max = arr[i];
    }

    return max;
}

int getSecondlargest(int arr[], int size, int max) {
    int second_largest = arr[0];

    for (int i = 1; i < size; i++) {
        if (arr[i] > second_largest && arr[i] < max)
            second_largest = arr[i];
    }

    return second_largest;
}

void printNLargest(int arr[], int size, int N) {
    int max = getMax(arr, size);
    int second_largest = max;
    printf("%3d", max);

    for (int i = 1; i < N; i++) {
        second_largest = getSecondlargest(arr, size, second_largest);
        printf("%3d", second_largest);
    }
}

int main(void) {
    int arr[] = { 50, 99, 20, 100, 76, 33, 87, 40, 81, 80 };
    int size = sizeof(arr) / sizeof(arr[0]);
    int N = 4;

    printNLargest(arr, size, N);

    return 0;
}




/*
run:

100 99 87 81

*/

 



answered May 16, 2022 by avibootz

Related questions

1 answer 109 views
1 answer 99 views
1 answer 104 views
1 answer 100 views
1 answer 108 views
1 answer 108 views
1 answer 94 views
...