Search code examples
c#listconsole

How can i add variables to my List by reading the User Input?


Im a Beginner in C#, and would like to add to my List via. reading the Input of the User.

class Program
{
    static void Main(string[] args)
    {
        List<int> list = new List<int>();


        Console.WriteLine("Asking a random Question here");

        // lacking Knowledge here **
         ** = Convert.ToInt16(Console.ReadLine());

        Console.ReadKey();
    }

Solution

  • So for the sake of a detailed example to the question here's a program that will average the numbers listed in standard input, one per line. It shows how to add a given number to the list as well.

        using System;
        using System.Collections.Generic;
    
        namespace AverageNumbers
        {
            class MainClass
            {
                public static void Main (string[] args)
                {
                    // Here is the list of numbers
                    List<int> numbers = new List<int>();
    
                    // Here are two variables to keep track
                    // of the input number (n), and the sum total (sum)
                    int n, sum = 0;
                    // This while loop waits for user input and converts
                    // that input to an integer
                    while (int.TryParse(Console.ReadLine(), out n))
                    {
                        // Here we add the entered number to the sum
                        sum += n;
                        // And to the list to track how many we've added       
                        numbers.Add(n);
                    }
    
                    // Finally we make sure that we have more than 0 numbers that we're summing and write out their average
                    Console.WriteLine("Average: " + (numbers.Count > 0? sum / numbers.Count : 0));
                }
            }
        }