C (programming language)
C program to find maximum between two numbers using switch case
C Program to Find Maximum Between Two Numbers Using Switch Case
Understanding the Problem
- We’ll explore an unconventional approach to find the maximum between two numbers using a switch case statement.
- While not the most common method for this task, it demonstrates the flexibility of switch cases.
Steps and Code:
- Include header file:
C
#include <stdio.h>
- Declare variables:
C
int num1, num2, max;
- Get input from the user:
C
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
- Apply switch case logic:
C
switch (num1 > num2) {
case 1:
max = num1;
printf("The maximum number is: %d", max);
break;
default:
max = num2;
printf("The maximum number is: %d", max);
}
Explanation:
- The
switch
statement evaluates the expressionnum1 > num2
.- If
num1
is greater thannum2
, the expression evaluates to 1, and thecase 1:
block executes, assigningnum1
tomax
. - If
num1
is not greater thannum2
, thedefault:
block executes, assigningnum2
tomax
.
- If
Key Points:
- This approach is less common than using if-else statements or conditional operators for this task.
- It demonstrates the ability of switch cases to handle simple comparisons and conditional logic.
- Consider clarity and readability when choosing a method for finding the maximum value.
- For more complex comparisons or multiple conditions, if-else statements or conditional operators are typically preferred.