Conditional Operator in C ( ?: ) with Example

Flow Control
If-else Statement in C
Programs on if-else
Switch Case in C
Switch case Programs
Conditional Operator
While loop in C
Do-while loop in C
While vs do-while
For loop in C
Break keyword in C
Continue keyword in C
Break vs Exit in C
Goto keyword in C
☕️ Flow Control Programs
Largest in 3 Numbers
Find Grade of student
Find the absolute value
Vowel or Consonant
Leap Year Program
Simple calculator in C
Check Odd or Even 
Roots of Quadratic Equation
Find Reverse of Number
Factors of a number in C
Generate Multiplication table
Find Power of a Number
Find GCD and LCM
Find factorial of Number
Count Number of Digits
Sum of digits in Number
Sum of N Natural Numbers
Sum of Squares of Natural No.
Find Sum of Odd Numbers
Find the Sum of Series
Find Fibonacci series in C
Sum of the Fibonacci series
Sum until enters +ve numbers
Sum of max 10 no. & Skip -ve
☕️ C Conversion Programs
Celsius to Fahrenheit
Fahrenheit to Celsius
Decimal ↔ Binary
Decimal ↔ Octal
Octal ↔ Binary in C
☕️ Number Programs in C
Prime Number in C
Strong Number in C
Krishnamurthy Number
Neon Number in C
Palindrome number
Perfect Number in C
Armstrong Number
☕️ Pattern Programs in C
Pattern programs in C
Printing pattern using loops
Floyd’s triangle Program
Pascal Triangle Program
Pyramid Star Pattern in C
Diamond Pattern Programs
Half Diamond pattern in C
Print Diamond Pattern
Hollow Diamond Pattern
Diamond Pattern of Numbers

The conditional operator in C is similar to the if-else statement. The if-else statement takes more than one line of the statements, but the conditional operator finishes the same task in a single statement. The conditional operator in C is also called the ternary operator because it operates on three operands.

What is a Conditional Operator in C

The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements that depend upon the output of the expression. As a conditional operator works on three operands, so it is also known as the ternary operator.

The operands may be an expression, constants, or variables. It starts with a condition, hence it is called a conditional operator. Conditional operators return one value if the condition is true and returns another value if the condition is false.


Syntax of Conditional Operator in C

expression1 ? expression2 : expression3;

or for simplicity, we write it as

condition ? true-statement : false-statement;

The expression1 is evaluated, it is treated as a logical condition. If the result is non-zero then expression2 will be evaluated otherwise expression3 will be evaluated. The value after evaluation of expression2 or expression3 is the final result.

The conditional operator in C works similarly to the conditional control statement if-else. Hence every code written using a conditional operator can also be written using if-else. When compared with if-else, conditional operator performance is high.

 if(expression1)
 {
     expression2;
 }
 else
 {
     expression3;
 }

Conditional Operator Example

Write a C program to find the maximum in the given two numbers using the conditional operator.

#include<stdio.h>
int main()
{
  float num1, num2, max;

  printf("Enter two numbers: ");
  scanf("%f %f", &num1, &num2);

  max = (num1 > num2) ? num1 : num2;

  printf("Maximum of %.2f and %.2f = %.2f",
                num1, num2, max);

  return 0;
}

Output:-

Enter two numbers: 12.5 10.5
Maximum of 12.50 and 10.50 = 12.50

First the expression, (num1 > num2) is evaluated. Here num1=12.5 and num2=10.5; so expression (num1>num2) becomes true. Hence num1 is the maximum number, and it is assigned to the variable max.

Output for another test:-

Enter two numbers: 9 20
Maximum of 9.00 and 20.00 = 20.00

Here num1=9 and num2=20; so the expression (num1>num2) becomes false. Hence num2 is the maximum number and it is assigned to the variable max.

The parentheses in the conditional operator are not necessary around the first expression of a conditional expression. The precedence of conditional operator ?: is very low. But it is advisable to use parentheses, however, it makes the condition part of the expression easier to see.

The above program using a conditional operator is similar to the below program using the if-else conditional statement.

#include<stdio.h>
int main()
{
  float num1, num2, max;
  printf("Enter two numbers: ");
  scanf("%f %f", &num1, &num2);
   
  if(num1>num2)
  {
    max = num1;
  }
  else
  {
    max = num2;
  }
   
  printf("Maximum of %.2f and %.2f = %.2f", 
                          num1, num2, max);

  return 0;
}

We will see more examples Later, first, let us see some popular MCQ based on the conditional operator in C language.


More Example of Conditional Operator in C

1) Program description:- Find the number is positive or negative using the conditional operator.

#include<stdio.h>
int main()
{
  int num;
  printf("Enter a number: ");
  scanf("%d", &num);
  (num>=0)?printf("Positive."):printf("Negative");
  return 0;
}

Output for the different test-cases:-

Enter a number: 8
Positive.

Enter a number: -10
Negative

2) Program description:- Find the given number is odd or even using the conditional operator in C.

#include<stdio.h>
int main()
{
  int num;
  printf("Enter a number: ");
  scanf("%d", &num);
  (num%2==0)? printf("Even"): printf("Odd");
  return 0;
}

Output for the different test-cases:-

Enter a number: 9
Odd

Enter a number: 8
Even

3) Program description:- Program to Find the minimum of two numbers using the conditional operator.

#include<stdio.h>
int main()
{
  float num1, num2, min;
  printf("Enter two numbers: ");
  scanf("%f %f", &num1, &num2);
  min = (num1 < num2) ? num1 : num2;
  printf("Minimum = %.2f", min);
  return 0;
}

Output for the different test-cases:-

Enter two numbers: 10 8
Minimum = 8.00

Enter two numbers: 15 12
Minimum = 12.00

4) Program description:- Write a program to enter two numbers. Make a comparison between them with the conditional operator. If the first number is greater than the second, perform a division operation otherwise multiplication operation.

#include<stdio.h>
int main()
{
  float a,b,result;
  printf("Enter two number: ");
  scanf("%f %f", &a, &b);
  result = (a>b)? a/b : a*b;
  printf("Result: %.2f",result);
  return 0;
}

Output for the different test-cases:-

Enter two number: 10 20
Result: 200.00

Enter two number: 10 5
Result: 2.00

5) Another good example of the conditional operator is,

#include<stdio.h>
int main()
{
  int item;
  printf("Enter the number of items: ");
  scanf("%d",&item);
  printf("You have %d item%s.", item, (item==1)?"":"s");
  return 0;
}

Output for the different test-cases:-

Enter the number of items: 1
You have 1 item.

Enter the number of items: 2
You have 2 items.

More than One Conditional Operator in a Statement

We can use more than one conditional operator in a statement. But in this case, it makes harder to understand the code. Use the ternary operator only when the resulting statement is short. This will make your code concise and much more readable.

Ternary operators can be used to replace multiple lines of code to a single line of code.

if(expression1)
{
  value = 1;
}
else if(expression2)
{
  value = 2;
}
else if(expression3)
{
  value = 3;
}
else
{
  value = 0;
}

The above multiple lines of code can be replaced with,

value = (exp1)?1:(exp2)?2:(exp3)?3:0;

Conditional Operator in C for Three Variables

Program Description:- Find the largest among three numbers using the conditional operator.

Program to find the maximum of three numbers using conditional operators.

#include<stdio.h>
int main()
{
  float a, b, c, max;
  printf("Enter three numbers: ");
  scanf("%f %f %f",&a, &b, &c);
  max = (a>b && a>b)? a: (b>a && b>c)? b:c;
  printf("Maximum number = %.2f",max);
  return 0;
}

Output for the different test-cases:-

Enter three numbers: 10 30 12
Maximum number = 30.00

Find the output of the below code?

#include<stdio.h>
int main()
{
  int a, num=500;
  a = (num>10?(num<=100?100:420):900);
  printf("%d",a);
  return 0;
}

The output of the above program: 420

#include<stdio.h>
int main()
{
  int a;
  a = 1?2?3?4?5:6:7:8:9;
  printf("%d",a);
  return 0;
}

The output of the above program: 5

MCQ

Choose a C conditional Operator from the list

MCQ1) Choose a C conditional operator from the list?

A) ? :
B) : ?
C) : <
D) < :

Answer:- A) ? :

We have already seen the syntax of the conditional operator. The syntax for the conditional operator is:- expression1 ? expression2 : expression3;

Choose a Syntax for C Ternary Operator from the List

MCQ2) Choose a syntax for C ternary operator from the list?

A) condition ? expression1 : expression2
B) condition : expression1 ? expression2
C) condition ? expression1 < expression2
D) condition < expression1 ? expression2

Answer:- A) condition ? expression1 : expression2

If the condition is true, expression 1 is evaluated. If the condition is false, expression 2 is evaluated. The conditional operator is also called a ternary operator.


FAQ

Q1) What is a conditional operator in C with example?

The conditional operator in C is a conditional statement that returns the first value if the condition is true and returns another value if the condition is false. It is similar to the if-else statement. The if-else statement takes more than one line of the statements, but the conditional operator finishes the same task in a single statement. 

Q2) What is conditional operator write syntax?

The syntax for the conditional operator in C is:- expression1? expression2: expression3; Here the expression1 is evaluated and treated as a logical condition. If the result is non-zero then expression2 will be evaluated otherwise expression3 will be evaluated. The value after evaluation of expression2 or expression3 is the final result. Or for simplicity, we can also write it like- condition? true-statement : false-statement;

Q3) What is a conditional operator used in C?

The conditional operator is used to check whether the given condition is true or false. If the condition is true then perform this task else perform another task. For example- expression1? expression2: expression3; Here the expression1 is evaluated, it is treated as a logical condition. If the result is non-zero then expression2 will be evaluated otherwise expression3 will be evaluated.

Q4) What is the function of the conditional operator?

Conditional operators are used to evaluating a condition that’s applied to one or two boolean expressions. The result of the evaluation is either true or false.

Q5) What is the symbol used for the conditional operator?
The symbol used for the conditional operator in C is ?:

Q6) How many arguments the conditional operator takes?

The ternary operator takes three arguments: The first is a comparison argument. The second argument is the result of a true comparison, and the third argument is the result of a false comparison.

Q7) What is the other name for the conditional operator?
The other name for the conditional operator is the ternary operator.

Q8) Why conditional operator is called the ternary operator?

Since the conditional operator in C works on three operands therefore it is also called a ternary operator. The operands may be an expression, constants, or variables.


If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Follow Us
Instagram • Twitter • Youtube • Linkedin • Facebook • Pinterest • Telegram

Flow Control
If-else Statement in C
Programs on if-else
Switch Case in C
Switch case Programs
Conditional Operator
While loop in C
Do-while loop in C
While vs do-while
For loop in C
Break keyword in C
Continue keyword in C
Break vs Exit in C
Goto keyword in C
☕️ Flow Control Programs
Largest among 3 Numbers
Find Grade of student
Find the absolute value
Check Vowel or Consonant
Leap Year Program
Simple calculator in C
Check Odd or Even 
Roots of Quadratic Equation
Find Reverse of Number
Factors of a number in C
Generate Multiplication table
Find Power of a Number
Find GCD and LCM
Find factorial of Number
Count Number of Digits
Sum of digits in Number
Sum of N Natural Numbers
Sum of Squares of Natural No.
Find Sum of Odd Numbers
Find the Sum of Series
Find Fibonacci series in C
Sum of the Fibonacci series
Sum until enters +ve numbers
Sum of max 10 no. & Skip -ve
☕️ C Conversion Programs
Celsius to Fahrenheit
Fahrenheit to Celsius
Decimal ↔ Binary
Decimal ↔ Octal
Octal ↔ Binary in C
☕️ Number Programs in C
Prime Number in C
Strong Number in C
Krishnamurthy Number
Neon Number in C
Palindrome number
Perfect Number in C
Armstrong Number
☕️ Pattern Programs in C
Pattern programs in C
Printing pattern using loops
Floyd’s triangle Program
Pascal Triangle Program
Pyramid Star Pattern in C
Diamond Pattern Programs
Half Diamond pattern in C
Print Diamond Pattern
Hollow Diamond Pattern
Diamond Pattern of Numbers

Leave a Comment

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