In C programming, finding the largest number among a given set of numbers is a fundamental exercise. In this blog post, we’ll write a C program that uses the nested if-else statement to find the maximum of three numbers entered by the user. Understanding how to use nested conditions is essential for solving problems where multiple conditions need to be evaluated.
Why Use Nested If-Else for Finding the Maximum?
A nested if-else statement is a decision-making structure that allows you to check multiple conditions in a sequential manner. This method is particularly useful when you have to compare multiple numbers and decide which one is the largest.
Using nested if-else allows you to evaluate one condition and then move to another condition based on the result of the first. In this case, we’ll use it to compare three numbers and find the maximum.
C Program to Find the Maximum of Three Numbers Using Nested If-Else
#include <stdio.h> int main() { int num1, num2, num3; // Input three numbers from the user printf("Enter three numbers: "); scanf("%d %d %d", &num1, &num2, &num3); // Find the maximum using nested if-else if (num1 >= num2) { if (num1 >= num3) { printf("The maximum number is %d\n", num1); } else { printf("The maximum number is %d\n", num3); } } else { if (num2 >= num3) { printf("The maximum number is %d\n", num2); } else { printf("The maximum number is %d\n", num3); } } return 0; }
Sample Input and Output
Example 1:
Input:
Enter three numbers: 25 30 20
Output:
The maximum number is 30
Example 2:
Input:
Enter three numbers: 15 12 18
Output:
The maximum number is 18
Example 3:
Input:
Enter three numbers: 10 10 10
Output:
The maximum number is 10
Explanation of the Code
- The program first reads three integer values from the user.
- The outer
if
statement comparesnum1
withnum2
. Ifnum1
is greater than or equal tonum2
, it then checks ifnum1
is greater than or equal tonum3
. If true,num1
is the maximum. - If
num1
is not the largest, the program comparesnum2
andnum3
in the nestedelse
block. Based on the comparison, it prints the maximum number. - This structure allows the program to evaluate conditions efficiently, ensuring the correct maximum value is printed.
Why Use Nested If-Else?
Nested if-else allows for more complex decision-making in your program. For example:
- You can extend this to find the minimum of three numbers as well.
- It’s useful when the conditions are interdependent, such as comparing multiple sets of values in a sequence.
By using nested if-else, you can implement more advanced logic and solve a variety of problems involving multiple comparisons.