David Prun David Prun -3 years ago 59
C Question

Biggest of 3 numbers code confused me

I wrote a piece of code which attempts to tell which of three user-inputted numbers is the greatest. However, I am unable to understand why my code breaks for the input

3, 1, 2
and works for the input
55, 54, 56
.

My code:

main()
{
int a,b,c;
printf("enter three numbers");
scanf("%d %d %d",&a,&b,&c);
if(a>b && a>c)
printf("%d is greatest",a);
if(b>a && b>c)
printf("%d is greatest",b);
else printf("%d is greatest",c);
getch();
}


What am I doing that causes this error, and what can I do to fix it?

Answer Source

You are missing "else if", that's for sure.

main()
{
    int a,b,c;
    printf("enter three numbers: ");
    scanf("%d %d %d",&a,&b,&c);

    if(a>b && a>c)
        printf("%d is greatest",a);
    else if(b>a && b>c)
        printf("%d is greatest",b);
    else 
        printf("%d is greatest",c);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download