Conditional operator programming exercises
C program to find maximum between three numbers using conditional operator
Write a C program to input three numbers from user and find maximum between three numbers using conditional/ternary operator ?:. How to find maximum between three numbers using conditional operator.
Required knowledge
Operators, Data Types in c, Variables in C
Program to find maximum between three numbers
/** * C program to find maximum between three numbers using conditional operator */ #include <stdio.h> int main() { int num1, num2, num3, max; /* * Input three numbers from user */ printf("Enter first number: "); scanf("%d", &num1); printf("Enter second number: "); scanf("%d", &num2); printf("Enter third number: "); scanf("%d", &num3); /* * usin if...else and if...else...if statement * If num1 > num2 and num1 > num3 then * assign num1 to max * else if num2 > num3 then * assign num2 to max * else * assign num3 to max */ max = (num1 > num2 && num1 > num3) ? num1 : (num2 > num3) ? num2 : num3; printf("\nMaximum between %d, %d and %d = %d", num1, num2, num3, max); return 0; }
Important note: In the above conditional operator I have used proper separators (spaces and new lines) to add readability to code. Practice a good habit to add more and more separators in your code to make it clear.
Output:
Enter first number: 10 Enter second number: 20 Enter third number: 30 Maximum between 10, 20 and 30 = 30