Find the Largest of the three numbers in the C Program
Let’s find the largest of three numbers in a C program using if...else
statements. Below is an example program that accomplishes this task:
#include <stdio.h>
int main() {
// Declare variables to store the three numbers entered by the user
double n1, n2, n3;
// Prompt the user to enter three numbers
printf(“Enter three numbers: “);
// Read the three numbers entered by the user and store them in variables n1, n2, and n3
scanf(“%lf %lf %lf”, &n1, &n2, &n3);
// Check if n1 is greater than or equal to both n2 and n3
if (n1 >= n2 && n1 >= n3)
// If true, print n1 as the largest number
printf(“%.2lf is the largest number.”, n1);
// If n1 is not the largest, check if n2 is greater than or equal to both n1 and n3
else if (n2 >= n1 && n2 >= n3)
// If true, print n2 as the largest number
printf(“%.2lf is the largest number.”, n2);
// If both of the above conditions are false, n3 must be the largest
else
// Print n3 as the largest number
printf(“%.2lf is the largest number.”, n3);
return 0;
}
This C program prompts the user to enter three numbers and then determines which one is the largest among them. It uses a series of conditional statements (if
, else if
, else
) to compare the numbers and print the largest one.
Here’s how the program works:
- It declares three variables of type
double
to store the input numbers:n1
,n2
, andn3
. - It prompts the user to enter three numbers.
- It uses
scanf()
to read threedouble
values from the user. - It compares the values of
n1
,n2
, andn3
to determine which one is the largest. - It prints the largest number with two decimal places.
The program correctly handles cases where two or more numbers are equal, as it doesn’t rely on strict inequalities (>
, <
) but instead uses >=
and &&
to ensure that if two numbers are equal to the largest, only one is printed as the largest.
If you have any specific questions on C Program To Find Largest of Three Numbers about how any part of the code works, feel free to ask!
References
- EduSeekho: (https://eduseekho.com/c-program-to-find-largest-of-three-numbers/)
- Reddit: (https://www.reddit.com/r/Eduseekho/comments/1ao2dda/program_to_find_largest_of_3_numbers_in_c/)
- Stackoverflow: (https://stackoverflow.com/questions/77693022/a-program-to-find-the-largest-number-among-three-numbers)
- Github: (https://github.com/eduseekho/C-Programs)
- Quora: (https://www.quora.com/How-do-you-write-a-program-to-find-the-largest-three-numbers-using-a-logical-operator-in-C-programming/answer/Edu-Seekho)