Write a C program to input two numbers from user and find maximum between given two numbers using switch case. How to find maximum or minimum between two numbers using switch case in C programming. Logic to find maximum between two numbers using switch case.
Example
Input
Input first number: 12 Input second number: 40
Output
Maximum: 40
Required knowledge
Basic programming, Switch case
Logic to find maximum using switch case
Finding maximum is an easy stuff. You already know how to do that manually or using if else condition. I already explained logic to find maximum using if condition. Do check it if you haven't.
Getting back to logic using switch case. Finding maximum using switch case is little tricky. For this program instead of switching the variable. Here we will switch an expression inside switch case statement. Which means switch (variable) will be replaced by switch (expression).
Below is the step by step descriptive logic to find maximum using switch case.
- Read two numbers from user, store it in some variable say num1 and num2.
- Switch the expression switch (num1 > num2). Did you remember > is a relational operator. It returns either true(1) or false(0). Since the relational operator > evaluates either to 1 or 0. Hence there will be two cases.
- For case 1 num1 is maximum.
- For case 0 num2 is maximum.
Let us write the code for the given program
Program to find maximum using switch case
/** * C program to find maximum between two numbers using switch case */ #include <stdio.h> int main() { int num1, num2; /* * Read two numbers from user */ printf("Enter two numbers to find maximum: "); scanf("%d%d", &num1, &num2); //The condition num1 > num2 will return either 0 or 1 switch(num1 > num2) { /* If the condition num1>num2 is false */ case 0: printf("%d is maximum", num2); break; /* If the condition num1>num2 is true */ case 1: printf("%d is maximum", num1); break; } return 0; }
Note: The expression switch (num1 > num2) will return either 0 or 1. Case 0 means the expression num1 > num2 is true. Case 1 means the expression num1 > num2 is false.
Before moving on from this, check other approaches to code the solution of this program.
Enter two numbers to find maximum: 20 10 20 is maximum
Happy coding ;)
You may also like
- Switch programming exercise index
- C program to check whether an alphabet is vowel or consonant using switch case
- C program to print total number of days in a month using switch case.
- C program to print day of week using switch case
- C program to check whether a number is even or odd using switch case.
- C program to create simple Calculator using switch case.