C program to find maximum between three numbers using ternary operator

Category: C Program
Tags: #cprogram#conditional#ternary

Discover how to efficiently find the maximum among three numbers in C programming using nested conditional operators. Enhance your C coding skills with this tutorial on concise and effective comparison techniques.

Determining the maximum value among three numbers is a common task in programming. In this article, we'll explore how to create a simple C program to find the maximum of three numbers using the conditional (ternary) operator.

Understanding the Conditional Operator

The conditional operator ? : is a concise way to write conditional statements in C programming. It takes three operands and has the form: condition ? expression1 : expression2. If the condition evaluates to true, expression1 is executed; otherwise, expression2 is executed.

C program to find maximum between three numbers using ternary operator

Let's delve into the C programming language to create a program that finds the maximum of three numbers using the conditional operator.

#include <stdio.h>

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

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

    // Finding the maximum using conditional operator
    max = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3);

    // Displaying the maximum number
    printf("The maximum number among %d, %d, and %d is: %d", num1, num2, num3, max);

    return 0;
}

Output

Enter three numbers: 3 2 1
The maximum number among 3, 2, and 1 is: 3

Finding the Maximum: The program uses nested conditional operators to determine the maximum value among the three numbers and stores it in the variable max.

In this article, we've created a simple C program that efficiently finds the maximum value among three numbers using nested conditional operators. Leveraging conditional operators in C programming enables us to streamline conditional checks and determine the maximum among multiple values concisely.