C program to find maximum between two numbers using switch case

Previous Program Next Program

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.

  1. Read two numbers from user, store it in some variable say num1 and num2.
  2. 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.
  3. For case 1 num1 is maximum.
  4. 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.

Output
Enter two numbers to find maximum: 20
10
20 is maximum

Happy coding ;)

You may also like

Previous Program Next Program
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment