I have a homework where I have to make a program that asks numbers for ten times in a loop and in the end gives the sum of those ten numbers. But it also must be possible to stop the loop and give the sum of numbers when enter is pressed.
I have tried something like this in while loop, but it didn't also work:
if( Console.KeyAvailable && Console.ReadKey( true ).Key == ConsoleKey.Enter ) break;
Can anyone suggest solutions?
Thanks in advance!
{
int i = 0;
int number;
string number_s;
int sum = 0;
while (i < 10)
{
{
i++;
Console.WriteLine("Enter number:");
number_s = Console.ReadLine();
Int32.TryParse(number_s, out number);
sum += number;
}
}
Console.Write("Sum is: {0}", sum);
}
if(string.IsNullOrWhiteSpace(number_s)) break;ReadLineis blocking. It will wait until there is something and an Enter in the buffer.KeyAvailableandReadKeyare non-blocking. Thus they will either way encounter empty buffer: before you enter the number or afterReadLineemptied the buffer.