Operators in C | conditional operator

Conditional Operator/ ternary operator / ?: Operator

Syntax:
Variable= condition ? value1: value2

If the specified condition is true then value1 will be assigned to the variable otherwise value2 will be assigned to the variable.

Giving Variable is optional.

Example:
a=10,b=20
x=a>b?100:200; x=200;
x=a<b?100:200; x=100;

Question:1
C program to take input for 2 numbers, check and print the larger number?
Sol:

```#include<stdio.h>
int main()
{
int a,b,c;
printf("Enter 2 nos ");
scanf("%d %d",&a,&b);
c=a>b?a:b;
printf("Max no = %d\n",c);
return(0);
}```
```/* Output */
Enter 2 nos 25
63
Max no = 63```

Question:2
C program to take input for 2 numbers, check and print the smaller number?
Sol:

```#include<stdio.h>
int main()
{
int a,b,c;
printf("Enter 2 nos ");
scanf("%d %d",&a,&b);
c=a<b?a:b;
printf("Min no = %d\n",c);
return(0);
}```
```/* Output */
Enter 2 nos 25
96
Min no = 25
```

Question:3
C program to take input for 2 numbers, check and print the larger number without using a variable?
Sol:

```#include<stdio.h>
int main()
{
int a,b;
printf("Enter 2 nos ");
scanf("%d %d",&a,&b);
a>b?printf("Max no %d",a):printf("Max no %d",b);
return(0);
}```
```/* Output */
Enter 2 nos 85
94
Max no 94
```

Question:4
C program to take input for 2 numbers, check and print the smaller number without using a variable?
Sol:

```#include<stdio.h>
int main()
{
int a,b;
printf("Enter 2 nos ");
scanf("%d %d",&a,&b);
a<b?printf("Min no %d",a):printf("Min no %d",b);
return(0);
}```
```/* Output */
Enter 2 nos 25
74
Min no 25
```

Important Pages