Wait, if you are like man, what the hell? This is a silly program and you’re like we all have done it in our college or school. This has something more to it and you might find it interesting, so read on.

Now, most of us used to write some version of this:

public class FindLargest{
public static void main(String[] args){
int a = 10, b = 20, c = 30;
if(a >= b && a>=c){
System.out.println("Largest number is : " + a);
}
if(b >= a && b>=c){
System.out.println("Largest number is : " + b);
}
if(c >= a && c>=b){
System.out.println("Largest number is : " + c);
}
}
}

Can this solution be improved? Yes. How?

public class FindLargest{
public static void main(String[] args){
int a = 10, b = 20, c = 30;
int largest = findLargest(a, b, c);
System.out.println("The largest number is : " + largest);
}
public static int findLargest(int a, int b, int c){
int largest = a;
if(b > largest){
largest = b;
}
if(c > largest){
largest = c;
}
return largest;
}
}

What is nice about the above code is that it’s neat and easy to understand. Rather than just blindly checking each number is larger than the other two, we assume the first number to be the largest and assign it to a variable called ‘`largest`

’. Then, we check if the other number is larger than the ‘`largest`

’. If it is, then we assign that number to variable ‘`largest`

’. We do this for each number. So at the end of all these comparisons, we should have the largest number in our ‘`largest`

’ variable and we would just return it! Another thing to note here is that we have reduced the number of comparisons by 1. Also see that this code is easy to **modify **for 4 or more numbers.

Now, if you are like ‘dude, isn’t there a way to write this code so that I don’t have to modify it if I change my mind later and want it to work with n numbers?!!’ fortunately there is.’

So, what is the solution?

Yes, the answer is `varargs`

. And here is the code:

public class FindLargest{
public static void main(String[] args){
int a = 10, b = 20, c = 30, d = 50;
int x = 5;
int p = 9, q = 3;
System.out.println("The largest number is : " + findLargest(a, b, c, d));
System.out.println("The largest number is : " + findLargest(x));
System.out.println("The largest number is : " + findLargest(p, q));
}
public static int findLargest(int a, int... nums){
int largest = a;
for(int num : nums){
if(num > largest){
largest = num;
}
}
return largest;
}
}

You can find this code in Java and Ruby here.

I hope you find this post helpful. And if you have any doubts or suggestions, feel free to drop a comment.

The post How to find the largest of 3 numbers appeared first on Bhargav's Blog.