Calculate Maximum and Minimum of Three Numbers in C Using if…else
1. Introduction
Learning how to find the maximum and minimum of numbers is a fundamental skill for beginner C programmers. It helps you understand decision-making in programming.
2.Problem Statement
Question: Write a C program to calculate the maximum and minimum of three numbers using the if…else statement.
3. Logic
To find the maximum and minimum of three numbers:
- Compare the first number with the second and third to determine the maximum.
- Similarly, compare the numbers to find the minimum.
- Use nested
if…elsestatements to check each condition step by step.
4. Source Code
Here is a beginner-friendly C program to solve this problem:
#include <stdio.h>
int main() {
int num1, num2, num3, max, min;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
// Find maximum
if(num1 >= num2 && num1 >= num3) {
max = num1;
} else if(num2 >= num1 && num2 >= num3) {
max = num2;
} else {
max = num3;
}
// Find minimum
if(num1 <= num2 && num1 <= num3) {
min = num1;
} else if(num2 <= num1 && num2 <= num3) {
min = num2;
} else {
min = num3;
}
printf("Maximum number: %d\n", max);
printf("Minimum number: %d\n", min);
return 0;
}
5. Sample Output
Enter three numbers: 12 45 7
Maximum number: 45
Minimum number: 7
6. Viva Questions
- Q: Which C statement is used to make decisions?
A:if…elsestatement. - Q: Can we find max and min without
if…else?
A: Yes, using conditional operators or built-in functions. - Q: What happens if two numbers are equal and maximum?
A: The program will still correctly assign the maximum using>=. - Q: Can this program handle negative numbers?
A: Yes, it works for both positive and negative numbers. - Q: What is the purpose of
scanfin this program?
A: To read three numbers input by the user.
