Find Smallest and Largest number in N numbers without using Array

Price: INR 1,299.00
Was: INR 1,799.00

This is most commonly asked question in Java Interview are, How do you find smallest and largest number in N numbers without using the Array in Java.

Well, Can you write the program to solve this problem? It’s easy to solve this problem.

To solve this issue, All you need to do is start with Integer.MIN_VALUE as smallest number and Integer.MAX_VALUE as largest number and loop through N numbers. At each iteration, compare the Iteration element value with the largest and smallest number, if the current number is larger than largest than its a new largest and if the current number is smaller than smallest than its a new smallest number.

Once you finish the iteration, you have the largest and smallest number without using an array. You can also assign the largest number as zero if there is no negative number in your input, but it won’t work if the user can enter both negative and positive integers.

 

Java Program to find Smallest and Largest number in N numbers without using the Array

In our sample program, we are finding the smallest and largest of N integers without using an array. This program handles both positive and negative number, hence largest value is initialized with Integer.MIN_VALUE and smallest number are initialized with Integer.MAX_VALUE.

If you are sure that your input will only be a positive number then you can initialize the largest with zero instead of Integer.MIN_VALUE. The program is simple, just take input from the user about how many numbers and then uses a for loop to get that many numbers as input by using Scanner.nextInt() method.

At the same time, we also keep comparing the largest and smallest numbers with the value entered by the user, so that at the end of the loop we have the largest and smallest number from the set of values entered by users.

 

OutPut :

 

 

You can see that our program has correctly printed the largest and smallest number from the 12 numbers entered by the user.

That’s all about how to calculate largest and smallest value in N numbers without using arrays. If you guys have any query than putting it in comments and we will be happy to answer your question.

0 Comment

Leave a Reply