EnderEgg
EnderEgg

Reputation: 335

How to know what is the second greatest number (of 3 numbers)? (C)

I want to know the "greatest", "greatest2", and "smallest" numbers. What I wrote doesn't work. Not even sure why. How can I fix this and If I had more numbers, is there a better option? Thanks in advance. (l1,l2,l3 would be the sides of a triangle) (also, it's in C)

greatest=l1;
    if(greatest<l2){
        greatest=l2;
    }if(greatest<l3){
        greatest=l3;
    }

    greatest2=l1;
    if(greatest2<l2&&l2<greatest){
        greatest2=l2;
    }if(greatest2<l3&&l3<greatest){
        greatest2=l3;
    }

    smallest=l1;
    if(smallest>l2){
        smallest=l2;
    }if(smallest>l3){  //had a mistake here, instead of > I had <
        smallest=l3;

I can mention that I don't really know much, but any advice is highly appreciated

Upvotes: 0

Views: 110

Answers (4)

darthir21
darthir21

Reputation: 57

If you had 3 numbers you can use:

if(a>c)
swap(a,c)

if (a > b)
swap(a, b)

//Now the smallest element is the first one. 

if (b > c)
swap(b, c);
//sorted 

If you had much more number than 3:

C/C++ standard library contains qsort function.

This is not the best quick sort implementation in the world but it fast enough and VERY EASY to be used... the formal syntax of qsort is:

qsort(,,sizeof(),compare_function);

int arr[] = {3,5,8};

qsort(values, 3, sizeof(int), cmpfunc);


for( n = 0 ; n < 3; n++ ) 
{   
   printf("%d ", values[n]);
}

Upvotes: 1

Carey Gregory
Carey Gregory

Reputation: 6846

Short and sweet:

greatest = l1 > l2 ? l1 > l3 ? l1 : l3 : l2 > l3 ? l2 : l3;
smallest = l1 < l2 ? l1 < l3 ? l1 : l3 : l2 < l3 ? l2 : l3;
middle = greatest == l1 ? (smallest == l2 ? l3 : l2) : greatest == l2 ? (smallest == l3 ? l1 : l3) : l2;

Upvotes: 2

mch
mch

Reputation: 9814

your assumption greatest2=l1; is incorrect if l1 is the second biggest. The correct code should be

if (l1 != greatest)
    greatest2 = l1;
else
    greatest2 = l2;

If you have an array of numbers:
You can do it in 1 loop: if you find a new maximum, the old maximum is the new second maximum, else if it is larger than the second, it is the new second maximum.

#include <stdio.h>

int main(void) {
    int a[] = {12,10,15,17,18,14,15,20};
    int max = a[0], second = a[0];
    unsigned size = sizeof a / sizeof a[0];
    if (size <= 1) //there would be no second number
        return -1;
    for (unsigned i = 1; i < size; i++)
    {
        if (a[i] >= max)
        {
            second = max;
            max = a[i];
        }
        else if (a[i] > second)
        {
            second = a[i];
        }
    }
    printf("max: %d, second: %d\n", max, second);
    return 0;
}

Upvotes: 1

mjr
mjr

Reputation: 2113

Put the numbers in a list(vector) and sort them.

http://www.cplusplus.com/reference/algorithm/sort/

Once they are in order, it is trivial to pick out the biggest, 2nd biggest, etc.

Upvotes: 0

Related Questions