Search code examples
c#loopsinputoutputaddition

How to get Numbers from user store them until they type -1 and than add all the numbers up toghterr


Hey i am trying to figure out the best way to get numbers from a user and than once the user types -1 it will add up all the numbers


Solution

  • This does as your question's described, you can test it here

    using System;
    using System.Text;
    using System.Linq;
    using System.Collections;
    using System.Collections.Generic;
                        
    public class Program
    {
        public static void Main()
        {
            List<int> numbers = new List<int>();
            Console.WriteLine("Enter your numbers below, 1 per line");
            string input = "";
            int inputNumber = 0;
            while((input = Console.ReadLine()) != "-1"){
                if(int.TryParse(input, out inputNumber)){
                   numbers.Add(inputNumber);
                }
            }
            int sum = numbers.Sum();
            Console.WriteLine("Total Sum: " + sum);
        }
        
    }