Q-14.(max_min) Write a program that takes two integers and find out the maximum and minimum between them.

0

Program to find maximum using simple if

/**
 * C program to find maximum between two numbers
 */

#include <stdio.h>

int main()
{
    int num1, num2;

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

    /* If num1 is maximum */
    if(num1 > num2)
    {
        printf("%d is maximum", num1);        
    }

    /* If num2 is maximum */
    if(num2 > num1)
    {
        printf("%d is maximum", num2);
    }

    /* Additional condition check for equality */
    if(num1 == num2)
    {
        printf("Both are equal");
    }

    return 0;
}
The above approach to check maximum between two numbers is easy to understand. However, instead of writing three conditions you can use if...else statement.

Program to find maximum between two numbers using if...else

/**
 * C program to find maximum between two numbers
 */

#include <stdio.h>

int main()
{
    int num1, num2;

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

    /* Compare num1 with num2 */
    if(num1 > num2)
    {
        /* True part means num1 > num2 */
        printf("%d is maximum", num1);        
    }
    else
    {
        /* False part means num1 < num2 */
        printf("%d is maximum", num2);
    }

    return 0;
}
You can also use a max variable. Assign maximum in the max variable based on if...else condition. Finally print the value of max.
In addition, as you can see in above programs if or else body contains only single statement. Hence, you can ignore braces { } after if and else statement.

Program to find maximum between two numbers

  1. /**
  2.  * C program to find maximum between two numbers
  3.  */

  4. #include <stdio.h>

  5. int main()
  6. {
  7.     int num1, num2, max;

  8.     /* Input two numbers from user */
  9.     printf("Enter two numbers: ");
  10.     scanf("%d%d", &num1, &num2);

  11.     /* Compare num1 with num2 */
  12.     if(num1 > num2)
  13.         max = num1;
  14.     else
  15.         max = num2;

  16.     printf("%d is maximum.", max);

  17.     return 0;
  18. }      




Post a Comment

0Comments
Post a Comment (0)