Basics · beginner
C Program to Find the Largest of Three Numbers
Find the largest of three numbers in C with if/else if/else and the && operator, then with nested conditional operators, including what happens with ties.
- if/else if/else
- relational operators
- logical &&
- conditional operator
Comparing three numbers is the classic exercise for if/else chains. C has no built-in max function for integers, so this is also how you write one yourself.
The program
#include <stdio.h>
int main(void) {
int a = 14, b = 27, c = 9;
int largest;
if (a >= b && a >= c)
largest = a;
else if (b >= a && b >= c)
largest = b;
else
largest = c;
printf("The largest number is %d\n", largest);
return 0;
}The largest number is 27How it works
- The first condition is true only if a is at least as big as both others. 14 >= 27 is false, so && stops evaluating.
- The else if tests b the same way; both comparisons hold, so largest becomes 27.
- The else branch handles the remaining case, where c is the largest.
- >= instead of > means ties still produce an answer: 5, 5, 3 gives 5.
Another way: A max function with the conditional operator
A small function makes the comparison reusable: max3 calls max2 twice. Nested ?: expressions also work but get hard to read quickly.
#include <stdio.h>
int max2(int x, int y) { return x > y ? x : y; }
int max3(int x, int y, int z) { return max2(max2(x, y), z); }
int main(void) {
printf("%d\n", max3(14, 27, 9));
printf("%d\n", max3(-5, -2, -9));
return 0;
}27
-2Common mistakes
- Writing if (a > b && c): "&& c" is true whenever c is not 0; it does not compare a with c.
- Using > everywhere, so with two equal largest values every condition is false and the wrong branch runs.
- Defining max as a macro #define MAX(x, y) x > y ? x : y without brackets, which breaks inside bigger expressions.
Try it yourself
- Read the three numbers with scanf and check its return value.
- Print the numbers in ascending order using only if statements.
Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 C examples, or write your own program in the online C Compiler.