C program to find maximum between two numbers using switch case

Write a C program to enter 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 in C programming.

Also view this program using -
C program to find maximum between two numbers using if else.
C program to find maximum between two numbers using conditional/ternary operator.
C program to find maximum or minimum between two numbers using functions.

Example:
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 using switch case is little tricky. For checking maximum between two number the condition we need is num1 > num2 (Where num1 and num2 are some integer values). This boolean expression will always return a single constant value i.e. true or false. And in C language boolean values are treated as integers i.e. 1 represents true and 0 represents false.

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;

    /*
     * Reads two numbers from user
     */
    printf("Enter two numbers to find maximum: ");
    scanf("%d %d", &num1, &num2);

    //The condition num1 > num2 will always return either 0 or 1
    switch(num1 > num2)
    {   
        /* If the condition num1>num2 is false */
        case 0: printf("\n%d is maximum", num2);
            break;
        /* If the condition num1>num2 is true */
        case 1: printf("\n%d is maximum", num1);
            break;
    }

    return 0;
}


Output
Enter two numbers to find maximum: 20
10

20 is maximum

Happy coding ;)


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
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment