I am writing a program that uses a while loop to determine the largest number input so far. I have to input 10 numbers in whole. At the end of the loop, it should output the largest number.

import java.util.Scanner;

public class Largest
{
	public static void main(String[] args)
	{
		int counter = 1;
		int number;
		int largest;
		int number2;
		
		Scanner input = new Scanner(System.in);
		
		while (counter < 10)
		{
			System.out.println("Enter a number");
			number = input.nextInt();
                  
                      // ???
                 }

At any given point there is one largest number. Either the new number isn't larger than the previous largest number, or it is. What do you do in the first case? What do you do in the second?

Well I edited it to make it to where it could get the largest number out of each iteration of the loop, but it wants the largest number in all, like out of the 10 numbers. I can't think of a way to do this without an array.

while (counter < 10)
		{
			System.out.println("Enter a number");
			number = input.nextInt();
			
			System.out.println("Enter another number");
			number2 = input.nextInt();
			
			if (number > number2)
				largest = number;
			else
				largest = number2;
				
				counter++;
				
				System.out.println(largest);
			}

Why do yo need a second number? You want to see if the new number is bigger than the largest number entered in previous iterations of the loop. Where is that value stored?

Idk, it just tells me to use at least these 3 variables

a) counter: A counter to count to 10 (i.e., to keep track of how many numbers have been
input and to determine when all 10 numbers have been processed).
b) number: The integer most recently input by the user.
c) largest: The largest number found so far.

And that's all you need. You don't need to input a second number in the loop.

Suppose you're in the middle of the loop, you know you've looked at five numbers and the largest so far is, let's say, 76. Now we start the sixth time through, and the input is 98. What happens?

Then the largest number is still 98, but the variable keeps getting set each time it goes through. Idk how to implement that in an if statement.

Edited 6 Years Ago by BuhRock: n/a

If the new number is larger, you set largest. Otherwise, you do nothing.

if (number > largest) 
  largest = number;
This article has been dead for over six months. Start a new discussion instead.