Write a C program to input two numbers from user and find maximum between two numbers using switch case. How to find maximum or minimum between two numbers using switch case. Logic to find maximum between two numbers using switch case in C programming.
Input
Input first number: 12 Input second number: 40
Output
Maximum: 40
In my previous posts, I explained various ways to find maximum or minimum using other approaches.
Must learn –
In this post I will explain to find maximum using switch...case
. Finding maximum using switch...case
is little tricky and under-the-hood concept.
So, let us begin with prerequisites first.
Required knowledge
Basic C programming, Relational operator, Switch case statement
Logic to find maximum using switch...case
statement
In all our previous exercises on switch...case
we switched variable value. However, you can also write an expression inside switch
.
The expression num1 > num2
evaluates 1 if num1 is greater than num2 otherwise evaluates 0. So if we write switch(num1 > num2)
, there can be two possible cases case 0
and case 1
.
Step by step descriptive logic to find maximum using switch...case
.
- Input two numbers from user. Store it in some variable say num1 and num2.
- Switch expression
switch(num1 > num2)
. - For the expression
(num1 > num2)
, there can be two possible values 0 and 1. - Write
case 0
and print num2 is maximum. - Write
case 1
and print num1 is maximum.
Important note: There is no possibility of default
case in this program.
Program to find maximum using switch...case
statement
/**
* C program to find maximum between two numbers using switch case
*/
#include <stdio.h>
int main()
{
int num1, num2;
/* Input two numbers from user */
printf("Enter two numbers to find maximum: ");
scanf("%d%d", &num1, &num2);
/* Expression (num1 > num2) will return either 0 or 1 */
switch(num1 > num2)
{
/* If condition (num1>num2) is false */
case 0:
printf("%d is maximum", num2);
break;
/* If condition (num1>num2) is true */
case 1:
printf("%d is maximum", num1);
break;
}
return 0;
}
Output
Enter two numbers to find maximum: 20 10 20 is maximum
Happy coding 😉
Recommended posts
- 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.