Problem Statement: Given three numbers. Find the greatest of three numbers.
Examples:
Example 1: Input: 1 3 5 Output: 5 Explanation: Answer is 5.Since 5 is greater than 1 and 3. Example 2: Input: 1.123 1.124 1.125 Output: 1.125 Explanation: Answer is 1.125. Since 1.125 is greater than 1.123 and 1.124
Solution
Disclaimer: Don’t jump directly to the solution, try it out yourself first.
Solution 1: Using max()(C++)/ Math max()(Java)
Approach: Standard Library function
Synatax for C++: max({num1,num2,num3}) or max(num1,max(num1,num2))
Syntax for Java: Math.max(num1,Math.max(num2.num3))
Code:
C++ Code
#include<bits/stdc++.h>
using namespace std;
int main() {
double num1 = 1, num2 = 3, num3 = 5;
cout << "The maximum of the three numbers is "<<max(num1, (num2, num3));
}
Output:
The maximum of the three numbers is 5
Time Complexity: O(1).
Space Complexity: O(1)
Java Code
public class Main {
public static void main(String args[]) {
double num1 = 1.123, num2 = 1.124, num3 = 1.125;
System.out.println("The greatest of the three numbers is "+Math.max(num1, Math.max(num2, num3)));
}
}
Output:
The greatest of the three numbers is 1.125
Time Complexity: O(1).
Space Complexity: O(1).
Solution 2: Using if-else statements
Approach:
- If num1 is greater than num2 and num3 then print num1.
- If num2 is greater than num3 and num1 then print num2.
- Else print num3.
Code:
C++ Code
#include<bits/stdc++.h>
using namespace std;
int main() {
double num1 = 1, num2 = 3, num3 = 5;
if (num1 > num2 && num1 > num3) {
cout <<"The greatest of the three numbers is "<< num1;
}
else if (num2 > num1 && num2 > num3) {
cout <<"The greatest of the three numbers is "<< num2;
}
else {
cout <<"The greatest of the three numbers is "<< num3;
}
}
Output:
The greatest of the three numbers is 5
Time Complexity: O(1).
Space Complexity: O(1).
Java Code
public class Main {
public static void main(String args[]) {
double num1 = 1.123, num2 = 1.124, num3 = 1.125;
if (num1 > num2 && num1 > num3) {
System.out.println("The greatest of the three numbers is "+num1);
} else if (num2 > num1 && num2 > num3) {
System.out.println("The greatest of the three numbers is "+num2);
} else {
System.out.println("The greatest of the three numbers is "+num3);
}
}
}
Output:
The greatest of the three numbers is 1.125
Time Complexity: O(1).
Space Complexity: O(1).
Special thanks to Pranav Padawe for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article