C program to find maximum between three numbers using conditional/ternary operator

Write a C program to enter three numbers from user and find maximum between three numbers using conditional/ternary operator ( ?: ).

Also view this program using if else -
C program to find maximum between three numbers using if else.

Required knowledge:

Basic C programming, Conditional operator

Program:

/**
 * C program to find maximum between three numbers using conditional operator
 */

#include <stdio.h>

int main()
{
    int num1, num2, num3, max;

    /*
     * Read three numbers from user
     */
    printf("Enter three numbers: ");
    scanf("%d %d %d", &num1, &num2, &num3);

    /* Finds maximum between three */
    max = (num1>num2 && num1>num3) ? num1 :
          (num2>num3) ? num2 : num3;

    printf("\nMaximum between %d, %d and %d = %d", num1, num2, num3, max);

    return 0;
} 
Output
X
_
Enter three numbers: 10
20
30

Maximum between 10, 20 and 30 = 30

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