Problem Statement: Given three numbers x, y, and z of which aim is to get the largest among these three numbers.

Example:
Input: x = 7, y = 20, z = 56
Output: 56 // value stored in variable z
Flowchart For Largest of 3 numbers:

Algorithm to find the largest of three numbers:
1. Start
2. Read the three numbers to be compared, as A, B and C
3. Check if A is greater than B.
3.1 If true, then check if A is greater than C
If true, print 'A' as the greatest number
If false, print 'C' as the greatest number
3.2 If false, then check if B is greater than C
If true, print 'B' as the greatest number
If false, print 'C' as the greatest number
4. End
Approaches:
- Using Ternary operator
- Using if-else
Approach 1: Using Ternary operator
The syntax for the conditional operator:
ans = (conditional expression) ? execute if true : execute if false
- If the condition is true then execute the statement before the colon
- If the condition is false then execute a statement after colon so
largest = z > (x>y ? x:y) ? z:((x>y) ? x:y);
Illustration:
x = 5, y= 10, z = 3
largest = 3>(5>10 ? 5:10) ? 3: ((5>10) ? 5:10);
largest = 3>10 ? 3 : 10
largest = 10
Java
import java.io.*;
class GFG {
static int biggestOfThree( int x, int y, int z)
{
return z > (x > y ? x : y) ? z : ((x > y) ? x : y);
}
public static void main(String[] args)
{
int a, b, c;
int largest;
a = 5 ;
b = 10 ;
c = 3 ;
largest = biggestOfThree(a, b, c);
System.out.println(largest
+ " is the largest number." );
}
}
|
Output10 is the largest number.
Approach 2: Using the if-else statements
In this method, if-else statements will compare and check for the largest number by comparing numbers. ‘If’ will check whether ‘x’ is greater than ‘y’ and ‘z’ or not. ‘else if’ will check whether ‘y’ is greater than ‘x’ and ‘z’ or not. And if both the conditions are false then ‘z’ will be the largest number.
Java
import java.io.*;
class GFG {
static int biggestOfThree( int x, int y, int z)
{
if (x >= y && x >= z)
return x;
else if (y >= x && y >= z)
return y;
else
return z;
}
public static void main(String[] args)
{
int a, b, c, largest;
a = 5 ;
b = 10 ;
c = 3 ;
largest = biggestOfThree(a, b, c);
System.out.println(largest
+ " is the largest number." );
}
}
|
Output10 is the largest number.
Approach 3 : Using Collections.max() method and ArrayList
Java
import java.lang.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
int a, b, c;
a = 5 ;
b = 10 ;
c = 3 ;
ArrayList<Integer> x = new ArrayList<>();
x.add(a);
x.add(b);
x.add(c);
System.out.println(Collections.max(x)
+ " is the largest number." );
}
}
|
Output10 is the largest number.
Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of ArrayList.