Ternary
A ternary operator is a short form of an if-else statement that takes three parts (three operands) โ thatโs why itโs called ternary.
Syntax
condition ? value_if_true : value_if_false;
Find Largest of 3 Numbers
Java
int a = 10, b = 25, c = 15;
int max = (a > b)
? (a > c ? a : c)
: (b > c ? b : c);
System.out.println("Largest = " + max);
javascript
let a = 10, b = 25, c = 15;
let max = (a > b)
? (a > c ? a : c)
: (b > c ? b : c);
console.log("Largest =", max);
python
a, b, c = 10, 25, 15
max_val = a if (a > b and a > c) else (b if b > c else c)
print("Largest =", max_val)
Prime numbers in given range
java
public class Prime {
public static void main(String[] args) {
int first=10;
int last=50;
while(first<=last) {
int div=2;
boolean flag=true;
while(div<=first/2) {
if(first%div==0) {
flag=false;
break;
}
div+=1;
}
if(flag&& first>1) {
System.out.println(first + " is prime number");
}
first+=1;
}
}
}
python
first=10
last=50
while(first<=last):
div=2
flag=True
while(div<=first/2):
if(first%div==0):
flag=False
break
div+=1
if flag and first>1:
print(first , " is prime number");
first+=1
javascript
let first=10;
let last=50;
while(first<=last) {
let div=2;
let flag=true;
while(div<=first/2) {
if(first%div==0) {
flag=false;
break;
}
div+=1;
}
if(flag && first>1) {
console.log(first + " is prime number");
}
first+=1;
}
} }
output
Flowchart
GCD(GREATEST COMMON DIVISOR)
java
public class Gcd {
public static void main(String[] args) {
int no1=10;
int no2=20;
int small=(no1<no2)?no1:no2;
int gcd=0;
int div=2;
while(div<=small) {
if(no1%div==0 && no2%div==0) {
gcd=div;
}
div+=1;
}
System.out.println("GCD is: "+ gcd);
}
}
javascript
let no1=10;
let no2=20;
let small=(no1<no2)?no1:no2;
let gcd=0;
let div=2;
while(div<=small) {
if(no1%div==0 && no2%div==0) {
gcd=div;
}
div+=1;
}
console.log("GCD is: " , gcd);
python
no1=10
no2=20
small=(no1<no2)?no1:no2
gcd=0
div=2
while(div<=small):
if(no1%div==0 && no2%div==0):
gcd=div
div+=1
print("GCD is: " , gcd);
output
Flowchart




Top comments (0)