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

Read more - Program to find maximum using if else.

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.

  1. Input two numbers from user, store it in some variable say num1 and num2.
  2. Switch the expression switch (num1 > num2). Relational operator > returns either 1 (true) or 0(false). Since relational operator > evaluates either to 1 or 0. Hence there will be two cases.
  3. For case 1 num1 is maximum.
  4. For case 0 num2 is maximum.

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;

    /*
     * Input 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) returns 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.

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>