to find greatest of 4 numbers in c
#include <stdio.h>
int main() {
float num1, num2, num3, num4, max;
printf("Enter four numbers: ");
scanf("%f %f %f %f", &num1, &num2, &num3, &num4);
if (num1 >= num2 && num1 >= num3 && num1 >= num4) {
max = num1;
} else if (num2 >= num1 && num2 >= num3 && num2 >= num4) {
max = num2;
} else if (num3 >= num1 && num3 >= num2 && num3 >= num4) {
max = num3;
} else {
max = num4;
}
printf("The greatest number is %.2f\n", max);
return 0;
}
Explanation:
- #include <stdio.h>
: Includes the standard input-output C library.
- int main() { ... }
: Entry point of the program.
- float num1, num2, num3, num4, max;
: Declares five floating-point variables to store the four input numbers and the maximum among them.
- printf("Enter four numbers: ");
: Prompts the user to input four numbers.
- scanf("%f %f %f %f", &num1, &num2, &num3, &num4);
: Reads the four input numbers provided by the user.
- if (num1 >= num2 && num1 >= num3 && num1 >= num4) { ... }
: Checks if num1
is greater than or equal to num2
, num3
, and num4
. If true, assigns num1
to max
.
- else if (num2 >= num1 && num2 >= num3 && num2 >= num4) { ... }
: Checks if num2
is greater than or equal to num1
, num3
, and num4
. If true, assigns num2
to max
.
- else if (num3 >= num1 && num3 >= num2 && num3 >= num4) { ... }
: Checks if num3
is greater than or equal to num1
, num2
, and num4
. If true, assigns num3
to max
.
- else { ... }
: If none of the above conditions are met, assigns num4
to max
(implicitly the greatest number among the four).
- printf("The greatest number is %.2f\n", max);
: Displays the greatest number among the four entered by the user with two decimal places.
- return 0;
: Indicates successful completion of the main()
function.