0

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);
          }
4
  • When you press Enter your number_s will be set to an empty string (string.Empty) now you just need to check for that and use the break keyword to exit the loop Commented Dec 1, 2019 at 8:55
  • if(string.IsNullOrWhiteSpace(number_s)) break; Commented Dec 1, 2019 at 8:55
  • Just to explain why your attempt failed: ReadLine is blocking. It will wait until there is something and an Enter in the buffer. KeyAvailable and ReadKey are non-blocking. Thus they will either way encounter empty buffer: before you enter the number or after ReadLine emptied the buffer. Commented Dec 1, 2019 at 9:03
  • What do you want to do when the user enters "Lilian", or "Banana" instead of a number? Commented Dec 1, 2019 at 9:39

2 Answers 2

1

The below code should work fine.

while (i < 10)
{
    i++;
    Console.WriteLine("Enter number:"); 
    number_s = Console.ReadLine(); 
    if(string.IsNullOrEmpty(number_s))
        break;
    input = Convert.ToInt32(number_s);
    sum += input;
}
Console.WriteLine("The sum of the entered numbers are : {0}", sum);
Sign up to request clarification or add additional context in comments.

3 Comments

If the user enters "Harikrishnan" instead of a number, the previous number will get added again. Is that the desired behavior? I think not...
@ZoharPeled Convert.ToInt will throw an exception in this case. So your behaviour will not happen.
@Holger yes, that's correct. I think I've misread the answer (question was using int.TryParse so I assumed answer was using that too).
1

When you press Entery Key, the value in number_s will be empty. You just need to use

if(string.IsNullOrEmpty(number_s))
 break;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.