C program to find maximum between two numbers using switch case

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.

Example
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.

  1. Input two numbers from user. Store it in some variable say num1 and num2.
  2. Switch expression switch(num1 > num2).
  3. For the expression (num1 > num2), there can be two possible values 0 and 1.
  4. Write case 0 and print num2 is maximum.
  5. 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 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>