Problem Statement: Given two numbers. Find the greatest of two numbers.
Examples:
Example 1: Input: 1 3 Output: 3 Explanation: Answer is 3,since 3 is greater than 1. Input: 1.123 1.124 Output: 1.124 Explanation: Answer is 1.124,since 1.124 is greater than 1.123.
Solution
Disclaimer: Don’t jump directly to the solution, try it out yourself first.
Solution 1: Using max()(C++)/ Math max()(Java)
Approach: Using Library function
Syntax for C++: max(num1,num2)
Syntax for Java: Math.max(num1,num2)
Code:
C++ Code
#include<bits/stdc++.h>
using namespace std;
int main() {
int num1 = 1, num2= 3;
cout <<"The greatest of the two numbers is "<< max(num1, num2);
}
Output:
The greatest of the two numbers is 3
Time Complexity: O(1).
Space Complexity: O(1).
Java Code
public class Main {
public static void main(String args[]) {
int num1 = 1;
int num2 = 3;
System.out.println("The greatest of the two numbers is "+Math.max(num1, num2));
}
}
Output:
The greatest of the two numbers is 3
Time Complexity: O(1).
Space Complexity: O(1).
Solution 2: Using if-else statements
Approach: If num1 is smaller than num2 print num2 else print num1.
Code:
C++ Code
#include<bits/stdc++.h>
using namespace std;
int main() {
double num1 = 1.123, num2 = 1.124;
if (num1 < num2) {
cout <<"The greatest of the two numbers is "<<num2;
}
else {
cout <<"The greatest of the two numbers is " <<num1;
}
}
Output:
The greatest of the two numbers is 1.124
Time Complexity: O(1).
Space Complexity: O(1).
Java Code
public class Main {
public static void main(String args[]) {
double num1 = 1.123;
double num2 = 1.124;
if (num1 < num2) {
System.out.println("The greatest of two numbers is "+num2);
} else {
System.out.println("The greatest of two numbers is "num1);
}
}
}
Output:
The greatest of the two numbers is 1.124
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