+1-617-874-1011 (US)

  +44-117-230-1145 (UK)

Conditional Operator

Syntax:

Expression 1 ? Expression 2 : Expression 3

Meaning:

If the Expression 1 is true then the value returned will be given by Expression 2 otherwise it will be given by Expression 3

Example of Else – If:

#include <stdio.h>
#include <conio.h>
void main()
{
int result;
printf(“Enter your marks: ”);
scanf(“%d”,&result);

if (result >= 75)
printf("Passed: Grade A\n");
else if (result >= 60)
printf("Passed: Grade B\n");
else if (result >= 45)
printf("Passed: Grade C\n");
else
printf("Failed\n");

return;
}

Conditional Operator Homework Help

Example of Conditional Operator:

To find the maximum of a and b:

#include <stdio.h>
#include <conio.h>
int main()
{
int a,b,max;
printf(“Enter a and b: ”);
scanf(“%d %d”,&a,&b);

max = (a>b) ? a : b;
printf(“Maximum is %d”,max);

return;
}

Here the statement,

max = (a>b) ? a : b;
means,
if (a>b)
max = a;
else
max = b;

Topics in C Programming