C (programming language)

C program to find maximum between two numbers using conditional operator

Understanding the Problem

  • The goal is to write a C program that effectively determines the larger of two given numbers.
  • We’ll focus on using the conditional operator, also known as the ternary operator, to achieve this task in a concise and efficient manner.

Steps and Code

  1. Include the necessary header file:


#include <stdio.h>
  1. Declare variables to store the numbers and the maximum value:


int num1, num2, max;
  1. Prompt the user to enter the two numbers:


printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
  1. Apply the conditional operator to find the maximum value:


max = (num1 > num2) ? num1 : num2;
  • Explanation:
    • The conditional operator has three operands:
      • The condition to be checked (num1 > num2 in this case)
      • The value to be assigned if the condition is true (num1)
      • The value to be assigned if the condition is false (num2)
    • It’s a shorthand way of writing an if-else statement.
  1. Print the result:


printf("The maximum number is: %d", max);

Key Points

  • The conditional operator offers a compact and readable way to write conditional expressions.
  • It’s particularly useful for simple comparisons like finding the maximum or minimum value.
  • It can enhance code clarity when used appropriately.
  • It’s essential to ensure proper understanding of its syntax and behavior to avoid potential errors.


Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button