How to find the second biggest number in a set of random numbers in C

1 Answer

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

int findSecondMax(int total, int rndmax) {
    int max, before_max, n;

    max = before_max = n = rand() % rndmax + 1;
    printf("%d\n", n);

    for (int i = 1; i < total; i++) {
        n = rand() % rndmax + 1;
        printf("%d\n", n);
        if (n > max) {
            before_max = max;
            max = n;
        } else if (n > before_max) {
            before_max = n;
        }
    }

    return before_max;
}

int main(void) {
    srand(time(NULL));

    int secondMax = findSecondMax(10, 100);
    printf("The second biggest number is: %d\n", secondMax);

    return 0;
}



/*
run:

76
61
1
45
88
32
61
94
64
54
The second biggest number is: 88

*/


answered Sep 17, 2014 by avibootz
edited Oct 4, 2025 by avibootz
...