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);
}
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With