We help IT Professionals succeed at work.

# Find largest and smallest number without array

on
1,139 Views
I would like to implement a program like follows:

Prompt the user to enter a bunch of numbers till a sentinel is enter.
Only output the max and min once the sentinel is enter.

What sentinel should I use, if all numbers entered are +ve and -ve integer.

public class MinMax{

public void main(String args[]){

int counter=0;

while(true){
int firstNum;
if(counter==0){ firstNum=num;}
counter++;
max=min=firstnum;
if(num==SENTINEL){
if(num<min) println("Min:"+min)  ;
if(num<max) println("Max:"+min)  ;
break;
}//end if
}//end while

}//end main

}//end class
Comment
Watch Question

## View Solution Only

CERTIFIED EXPERT
Top Expert 2016

Commented:
You haven't defined min/max

int max = Integer.MIN_VALUE;
max = Math.max(max, num);
``````int max = Integer.MIN_VALUE; // (before loop)
...
max = Math.max(max, num);
``````
Top Expert 2009

Commented:
Can you ask the user how many number he wants to enter and then take as input that many numbers? Otherwise you might have to do some extra processing to get the numbers.

Commented:
To CEHJ,
Actually, this is an exercise that I try to sharpen my programming skill without using much reusable library and preferably write by my own functions.

To a_b,
Can you ask the user how many number he wants to enter and then take as input that many numbers?
Can not in this case.
Since this is an exercise that I try to sharpen my programming skill without using much reusable library and preferably write by my own functions.

Sorry Guys. :-)

CERTIFIED EXPERT
Top Expert 2016

Commented:
>>
Actually, this is an exercise that I try to sharpen my programming skill without using much reusable library and preferably write by my own functions.
>>

Well there's very little difference actually in doing what i suggested and doing the below, but either way, you need to define the variable:
``````if (max < num) {
max = num;
}
``````

Commented:
Hi CEHJ,
How about the integer sentinel, if I allow all integers to be enter?

Any other alternative? (refer my code above)

thanks.
CERTIFIED EXPERT
Top Expert 2016
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)

Commented:
CEHJ:
Yes, you are right.

I honors 250 marks to you.
CERTIFIED EXPERT
Top Expert 2016

Commented:
:-)
Unlock the solution to this question.