C (programming language)

C program to find maximum between two numbers using switch case

C Program to Find Maximum Between Two Numbers Using Switch Case

Understanding the Problem

  • We’ll explore an unconventional approach to find the maximum between two numbers using a switch case statement.
  • While not the most common method for this task, it demonstrates the flexibility of switch cases.

Steps and Code:

  1. Include header file:

C

#include <stdio.h>
  1. Declare variables:

C

int num1, num2, max;
  1. Get input from the user:

C

printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
  1. Apply switch case logic:

C

switch (num1 > num2) {
    case 1:
        max = num1;
        printf("The maximum number is: %d", max);
        break;
    default:
        max = num2;
        printf("The maximum number is: %d", max);
}

Explanation:

  • The switch statement evaluates the expression num1 > num2.
    • If num1 is greater than num2, the expression evaluates to 1, and the case 1: block executes, assigning num1 to max.
    • If num1 is not greater than num2, the default: block executes, assigning num2 to max.

Key Points:

  • This approach is less common than using if-else statements or conditional operators for this task.
  • It demonstrates the ability of switch cases to handle simple comparisons and conditional logic.
  • Consider clarity and readability when choosing a method for finding the maximum value.
  • For more complex comparisons or multiple conditions, if-else statements or conditional operators are typically preferred.

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button