C program to find maximum between two numbers using ternary operator

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

Learn how to efficiently find the maximum between two numbers in C using the conditional or ternary operator. Explore concise coding methods and enhance your C programming skills with this tutorial on comparing values.

In programming, determining the maximum value between two numbers is a common operation. In this article, we'll explore how to create a simple C program to find the maximum of two numbers using the conditional (ternary) operator.

Understanding the Conditional Operator

The conditional operator (also known as the ternary operator) ? : is a concise way to write an if-else statement. 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 two numbers using ternary operator

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

#include <stdio.h>

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

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

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

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

    return 0;
}

Output

Enter two numbers: 4 2
The maximum number between 4 and 2 is: 4

In this article, we've created a simple C program that efficiently finds the maximum value between two numbers using the conditional operator. Understanding and utilizing the conditional operator allows us to streamline conditional checks and make code concise in C programming.