Algorithm to Find the Largest Number Among Three Numbers
Step 1: Start
Step 2: Input: Read three integers a, b, and c from the user.
Step 3: Process:
Initialize a variable largest to store the largest number.
Compare a, b, and c to find the largest:
- If a is greater than b and a is greater than c, then a is the
largest.
- Otherwise, if b is greater than c, then b is the largest.
- Otherwise, c is the largest.
Step 4: Output: Display the largest number among a, b, and c.
Step 5: End
C Program to Find the Largest Number Among Three Numbers
#include <stdio.h>
int main() {
int a, b, c, largest;
// Step 2: Read three integers from the user
printf("Enter three integers (a, b, c): ");
scanf("%d %d %d", &a, &b, &c);
// Step 3: Find the largest number among a, b, and c
if (a >= b && a >= c) {
largest = a;
} else if (b >= a && b >= c) {
largest = b;
} else {
largest = c;
}
// Step 4: Output the largest number
printf("The largest number among %d, %d, and %d is %d.\n", a, b, c, largest);
// Step 5: End
return 0;
}
Explanation of Each Step
Include Header:
#include <stdio.h>
- This line includes the standard input-output library.
Main Function:
int main() {
- The main function is the entry point of the C program.
Variable Declaration:
int a, b, c, largest;
- Four integer variables are declared: a, b, c to store user inputs, and largest to store the largest number among them.
Reading Input:
printf("Enter three integers (a, b, c): ");
scanf("%d %d %d", &a, &b, &c);
- printf prompts the user to enter three integers.
- scanf reads the integers and stores them in variables a, b, c.
Finding the Largest Number:
if (a >= b && a >= c) {
largest = a;
} else if (b >= a && b >= c) {
largest = b;
} else {
largest = c;
}
- The if – else ladder compares a, b, and c to determine the largest:
- If
a
is greater than or equal to b and a is greater than or equal to c, then a is assigned to largest. - Otherwise, if b is greater than or equal to a and b is greater than or equal to c, then b is assigned to largest.
- Otherwise, c is assigned to largest.
- If
Output:
printf("The largest number among %d, %d, and %d is %d.\n", a, b, c, largest);
- This line prints the largest number among a, b and c using the printf function.
End:
return 0;
- This line indicates successful completion of the program.
This program effectively finds and displays the largest number among three integers provided by the user. The algorithm ensures that all possible cases (where each of a, b and c could be the largest) are covered by using conditional statements (if – else).
Discover more from lounge coder
Subscribe to get the latest posts sent to your email.