Loading your workspace…
Loading your workspace…
Read three integers and print the largest one, using an if-else ladder.
#include <stdio.h>
int main(void) {
int a, b, c, largest;
printf("Enter three integers:\n");
if (scanf("%d %d %d", &a, &b, &c) != 3) {
printf("Error: invalid input\n");
return 1;
}
if (a >= b && a >= c) {
largest = a;
} else if (b >= c) {
largest = b;
} else {
largest = c;
}
printf("Largest: %d\n", largest);
return 0;
}
Input
3 9 4Output
Enter three integers:
Largest: 9Input
5 5 5Output
Enter three integers:
Largest: 5The first test uses >= so that ties are handled without a special case. Once a is ruled out as the largest, only b and c remain, and the second test decides between them.
Using a ladder of conditions means each value is compared only as many times as needed.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
3 9 4
Expected output
Enter three integers: Largest: 9
5 5 5
Expected output
Enter three integers: Largest: 5
So that when two or more values are equal to the maximum, the program still returns that value.
Three comparisons, since the last branch needs no test.
Yes, for example largest = a > b ? a : b, nested for three values.
The number of values read. Checking for 3 catches missing input.
An else-if ladder stops at the first true condition, so only one value is assigned.
Back to all RCU 21BCA1C1P lab programs.