In this tutorial, we will write a basic C Program to find the greatest of three numbers. You may go through the following topics in order to understand the C program.
Algorithm to find the largest among three numbers
- Start.
- Read num1, num2 and num3 from user.
- Check num > num2, if true go to step 4 else go to step 5
- Check num1 > num3.
- If true, print ‘num1 is the greatest number’.
- If false, then print ‘num3 as the greatest number’.
- go to step 6
- check if num2 > num3.
- If true, print ‘num2 as the greatest number’.
- If false, print ‘num3 as the greatest number’.
- Stop
C Program to find the Largest among three Numbers
We will find the greatest of three using if..else and if…else-if statement.
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 | //C program to find the biggest of three numbers using if else if statement #include <stdio.h> int main() { int num1, num2, num3; printf("Enter three numbers to compare.\n"); printf("First Number: "); scanf("%d", &num1); printf("Second Number: "); scanf("%d", &num2); printf("Third Number: "); scanf("%d", &num3); if (num1 > num2) { if (num1 > num3) { printf("\nLargest number: %d \n",num1); } else { printf("\nLargest number: %d \n",num3); } } else if (num2 > num3) { printf("\nLargest number: %d \n",num2); } else { printf("\nLargest number: %d \n",num3); } return 0; } |
Output:
Enter three numbers to compare.
First Number: 32
Second Number: 65
Third Number: 19
Largest number: 65
Using Ternary operator
The ternary operator works like an if..else statement in C. Syntax of the ternary operator. (?:
)
variable num1 = (expression) ? value if true : value if false
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //Using ternary Operator #include <stdio.h> int main() { int num1, num2, num3; printf("Enter three numbers to compare.\n"); printf("First Number: "); scanf("%d", &num1); printf("First Number: "); scanf("%d", &num2); printf("First Number: "); scanf("%d", &num3); int greatestNum = ((num1>num2 && num1>num3) ? num1 : (num2>num3)?num2:num3); printf("\nLargest of three is: %d.", greatestNum); return 0; } |
Output:
Enter three numbers to compare.
First Number: 45
Second Number: 98
Third Number: 66
Largest of three is: 98