In this article, we will learn how to find the maximum of two numbers using switch case statements in C programming.
The program takes two integer inputs from the user and then prints the maximum of the two.
Sample Input:
Enter first number: 20
Enter second number: 40
Expected output:
40 is Largest
You can use the following approach to find the maximum of two numbers using the switch...case
statement:
- Declare two integer variables
num1
andnum2
to store the two numbers. Also declare a third integer variableexp
which we will use inside the switch statement. - Take the first number from the user using the scanf() function and store it in the
num1
variable. - Take the second number from the user using the scanf() function and store its value in the
num2
variable. - Store the value of the
num1 > num2
expression in the third variableexp
. The expressionnum1 > num2
returns 1 ifnum1
is larger thannum2
, otherwise, it returns 0. - Put the result of the
num > num2
expression i.e.exp
variable in the switch statement. - Put two cases, case 1 & case 0, inside the switch statement. The
case 1
runs if num1 is greater than num2, otherwise, thecase 0
runs.
The following C program shows how you can use the switch...case
statement to find the largest of the two numbers:
// C program to find the maximum of the two numbers using Switch Case #include <stdio.h> int main(){ // Declare variables int num1, num2, exp; // Get the first number printf("Enter first number: "); scanf("%d", &num1); // Get the second number printf("Enter second number: "); scanf("%d", &num2); // Returns 1 if num1 is greater than num2, otherwise, returns 0 exp = num1 > num2; switch(exp){ // Can become 1 or 0 only // Runs if num1 > num2 case 1: printf("%d is Largest", num1); break; // Runs if num1 < num2 case 0: printf("%d is Largest", num2); break; } return 0; }
Output:
Enter first number: 20 Enter second number: 40 40 is Largest
Please note that this program does not give the correct output if both numbers are equal to each other. If you also want to put an equality check, use the if…else statements instead.