Finding the Greatest Number Among Three - A C Code Implementation
Description:
This blog post presents a C code to find the greatest number among three user-input integers.
The code uses scanf to interact with the user and employs an optimized comparison logic to efficiently determine the largest value.
By eliminating unnecessary nested if statements, the program becomes more concise and easier to understand.
The post includes a commented version of the code, explaining each step of the process for better comprehension.
You can also use this way to approach this problem using arrays and loops:Click here.
#include <stdio.h>
int main()
{
int a, b, c;
// Prompt the user to enter three integers
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
printf("Enter third number: ");
scanf("%d", &c);
// Compare the three numbers to find the greatest
if (a > b)
{
if (a > c)
{
printf("%d is the greatest among all of these", a);
}
}
if (b > a)
{
if (b > c)
{
printf("%d is the greatest among all of these", b);
}
}
if (c > a)
{
if (c > b)
{
printf("%d is the greatest among all of these", c);
}
}
return 0;
}
Comments:
1. User Input: The program uses printf and scanf functions to interact with the user. It prompts the user to enter three integers (a, b, and c) and reads these values.
2. Comparison Logic: The code contains multiple nested if statements to compare the three numbers and find the greatest among them.
3. Optimizing the Comparison Logic: The current implementation can be improved by simplifying the nested if statements.
BUT THIS IS NOT THE BEST METHOD TO SOLVE THIS PROBLEM.
Simplified Version with Optimized Comparison Logic
#include <stdio.h>
int main()
{
int a, b, c;
// Prompt the user to enter three integers
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
printf("Enter third number: ");
scanf("%d", &c);
// Find the greatest number among the three
int greatest = a; // Assume the first number is the greatest
if (b > greatest)
{
greatest = b;
}
if (c > greatest)
{
greatest = c;
}
// Print the greatest number among the three
printf("%d is the greatest among all of these", greatest);
return 0;
}
Comments
Post a Comment