Program to demonstrate ternary operator
- Write a program to demonstrate ternary operators in C
- Write a program to demonstrate ternary operators in C++
- Write a program to demonstrate ternary operators in Python
- Write a program to demonstrate ternary operators in PHP
- Write a program to demonstrate ternary operators in Java
- Write a program to demonstrate ternary operators in Java Script
- Write a program to demonstrate ternary operators in C#
Explanation:
A straightforward conditional statement can be written more quickly by using the ternary operator. When the condition is simple, it frequently takes the role of if-else expressions.
Syntax:
condition ? expression_if_true : expression_if_false;
- condition: The boolean expression to evaluate.
- expression_if_true: The value or operation to execute if the condition is true.
- expression_if_false: The value or operation to execute if the condition is false.
Key points:
- Because it accepts three operands, it is known as the “ternary” operator.
- Usually, it is applied to brief assignments or return statements.
- Accessible in a variety of computer languages, including PHP, C#, Java, C, C++, and JavaScript.
- The syntax used by Python is a little different.
Program to demonstrate compound operators
-
C
-
C++
-
Python
-
PHP
-
JAVA
-
Java Script
-
C#
#include <stdio.h> int main() { int a = 5, b = 10; // Using ternary operator int max = (a > b) ? a : b; printf("The greater value between a and b is: %d\n", max); return 0; } printf("Value of a after prefix increment: %d\n", a); // Postfix decrement printf("Postfix decrement: %d\n", a--); printf("Value of a after postfix decrement: %d\n", a); // Prefix decrement printf("Prefix decrement: %d\n", --a); printf("Value of a after prefix decrement: %d\n", a); return 0; }
#include <iostream> int main() { int a = 5, b = 10; // Using ternary operator int max = (a > b) ? a : b; std::cout << "The greater value between a and b is: " << max << std::endl; return 0; }
a, b = 5, 10 # Using ternary operator (Python equivalent) max_value = a if a > b else b print(f"The greater value between a and b is: {max_value}")
<?php $a = 5; $b = 10; // Using ternary operator $max = ($a > $b) ? $a : $b; echo "The greater value between a and b is: $max\n"; ?>
public class Main { public static void main(String[] args) { int a = 5, b = 10; // Using ternary operator int max = (a > b) ? a : b; System.out.println("The greater value between a and b is: " + max); } }
let a = 5, b = 10; // Using ternary operator let max = (a > b) ? a : b; console.log(`The greater value between a and b is: ${max}`);
using System; class Program { static void Main() { int a = 5, b = 10; // Using ternary operator int max = (a > b) ? a : b; Console.WriteLine($"The greater value between a and b is: {max}"); } }