OverIQ.com

C Program to find the largest of three numbers

Last updated on September 23, 2020


The following is a C program to find the largest of the three numbers:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*********************************************
 Program to find the largest of three numbers
 **********************************************/

#include<stdio.h> // include stdio.h library

int main(void)
{       
    int a, b, c;

    printf("Enter a: ");
    scanf("%d", &a);

    printf("Enter b: ");
    scanf("%d", &b);

    printf("Enter c: ");
    scanf("%d", &c);

    if(a > b)
    {
        if(a > c)
        {
            printf("a is largest.");
        }
        else
        {
            printf("c is largest.");
        }
    }
    else
    {
        if(b > c)
        {
            printf("b is largest.");
        }
        else
        {
            printf("c is largest.");
        }
    }

    return 0; // return 0 to operating system
}

Try it now

Expected Output: 1st run:

1
2
3
4
Enter a: 45
Enter b: 100
Enter c: 20
b is largest.

2nd run:

1
2
3
4
Enter a: -10 
Enter b: -81
Enter c: -5
c is largest.

How it works #

The program starts off by asking the user to enter three digits (a, b and c).

In line 20, we check whether a is greater than b. If the condition a > b evaluates to true (1) the program control comes to the nested if statement in line 22 and checks whether a > c. If the condition a > c evaluates to true (1), then a is the largest number. Otherwise, c is the largest number.

If the condition in line 20, evaluates to false, then we can say for sure that b > a.

In line 33, we check whether b > c. If it is, then b is the largest number. if the condition fails, then we can conclude that c > b.

Since, b > a and c > b. Therefore, c > b > a. Hence, c is the largest number.


Recommended Reading: