Video Link: https://youtu.be/05xv2nMj6Ls Tutorial Link: https://www.programiz.com/c-programming
test_condition ? expression1 : expression2;
#include <stdio.h>
int main() {
int age = 15;
(age >= 18) ? printf("You can vote") : printf("You cannot vote");
return 0;
}
Output
You cannot vote
#include <stdio.h>
int main() {
int age = 24;
(age >= 18) ? printf("You can vote") : printf("You cannot vote");
return 0;
}
Output
You can vote
#include <stdio.h>
int main() {
char operator = '+';
int num1 = 8;
int num2 = 7;
int result = (operator == '+') ? (num1 + num2) : (num1 - num2);
printf("%d", result);
return 0;
}
Output
15
Q. Can you create a program to check whether a number is odd or even? To create this program, create a variable named number and assign a value to it. Then using a ternary operator check if the number variable is odd or even.
- If number is odd, print "The number is Odd"
- If number is even, print "The number is Even"
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
(number % 2 == 0) ? printf("It is even ") : printf("It is odd");
return 0;
}
Output
Enter a number: 5
It is odd
Q. What is the correct ternary equivalent of the following if...else statement?
if (5 > 3) {
result = 9;
}
else {
result = 3;
}
Options:
- result = 5 > 3 ? 3 : 5;
- 5 > 3 ? result = 5 : 3;
- result = 5 > 3 ? 5 : 3;
- 5 > 3 ? result = 3 : 5;
Answer: 3