More efficiently entering numbers via Serial port [SOLVED]

Hi everyone,

I've created a sketch which prompts the user to enter the size (between 1 and 100) of a list of numbers. The user is then prompted to enter a value for each number of the list. The numbers are then compared and the highest value in the list is printed. The code is as follows:

long i;
long n;
long arr[100];

void setup() {

Serial.begin(9600);
Serial.setTimeout(5000);
Serial.println("Enter total amount of numbers to consider (1-100):");
}

void loop() {
  
if(Serial.available() > 0){
n=Serial.parseInt();
  
for(i=0;i<n;i++)
{
  Serial.print("Enter value of number ");
  Serial.println(i+1);
  arr[i]=Serial.parseInt();}

for (i=1;i<n;i++)
{
  if (arr[0]<arr[i])
    {arr[0]=arr[i];
 }
}
Serial.print("Largest number entered is: ");
Serial.println(arr[0]);
Serial.println("Enter total amount of numbers to consider (1-100):");
 }
}

The sketch works, but I'm trying to come up with a more efficient way of entering the values. Ideally, what I'd like is for the user to be prompted for each value in the list and have the program wait until the value has been entered and then ask for the next value. As it is now, the Serial.setTimeout function allows a delay between each iteration of the for loop to wait for the user to type something, but also adds some lag to the program if the user enters in the value quickly.

I've done some reading on the Serial functions, but am not sure what the best solution for this is. Any ideas would be greatly appreciated.

There is a simple user input example in Planning and Implementing a Program

...R

Note: If you are only printing the highest number, there is no need to keep the whole list. Just keep the previous highest number.

Set your Serial Monitor line ending to something other than 'None' so you don't have to wait for the timeout.

Just before you prompt for an input, empty all characters from the input buffer:

while (Serial.available()) Serial.read();

Before you call Serial.parseInt(); make sure that new input has arrived so you don't start the timeout until the user sends you a line.

  if (Serial.available())
  {
     int value = Serial.parseInt();
  }

Note that if the user hits 'Enter' without typing a number, the value 0 will be returned by .parseInt(). If you want to ignore non-number inputs you will have to parse the input yourself.

Thanks for the input, everyone—all very helpful. In particular, I think the link that Robin2 provided might help me figure out what I'm trying to do as well as offering some good general advice on the most efficient way to structure a sketch. All the information is appreciated, though, and thanks for the replies.