Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2nd largest from 3 numbers, using if_else

Tags:

c

I'm kind of new to C programming and I recently bumped into a question of finding the 2nd largest number from 3 numbers. I tried it using if...else, but it is always giving the smallest number as output. What is the logical error I'm making in this code?

#include<stdio.h>

int main() {
    int a;
    int b;
    int c;
    a=10;
    b=30;
    c=7;
    if(a>b) {
        if(a>c) {
            if(b>c)
                printf("2nd largest is %d",c);
            else
                printf("2nd largest is %d",b);
        }
    } else

    {
        if(b>c) {
            if(c>a)
                printf("2nd largest is %d",a);
            else
                printf("2nd largest is %d",c);
        } else
            printf("2nd largest is %d",b);
    }
}
like image 641
Sagnik Avatar asked Oct 01 '22 08:10

Sagnik


1 Answers

if(a>b) {
    if(a>c) { //a is the greatest!
        if(b>c) // the *greater* of the two remaining is the second greatest
            printf("2nd largest is %d",c); // if b > c, output b!
        else
            printf("2nd largest is %d",b); // if c > b, output c! 
    } // I think this got missed:  What if c > a and a > b?
} else

{
    if(b>c) { //b is the greatest!
        if(c>a) //As above, the *greater* of the two remaining is what you are looking for
            printf("2nd largest is %d",a); // c is greater, so output it
        else
            printf("2nd largest is %d",c); // a is greater
    } else // c > b and b > a, this is correct.
        printf("2nd largest is %d",b);
}
like image 139
femtoRgon Avatar answered Oct 20 '22 07:10

femtoRgon