Search code examples
c#spaceseparator

Read array of integers from user which is separated by space in C#


I was asked to solve a problem in C# to get the sum of 'n' user inputs from console, which is separated by space, in a single line.

int n = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[n];
int sum = 0;
for(int i = 0; i < n; i++) {
   arr[i] = Convert.ToInt32(Console.ReadLine());
   sum += arr[i];
}
Console.WriteLine("{0}",sum);

How can I modify this code to get the expected output from the space separated input? Also the values need to be stored in array.

Input:

5

1 2 3 4 5

Output:

15


Solution

  • You could do something like this:

    int result = input.Split(' ').Take(n).Select(int.Parse).Sum();
    

    But it seems to me that you could avoid asking the user for the count, and just add together all the lines that they typed in:

    string input = Console.ReadLine();
    int result = input.Split(' ').Select(int.Parse).Sum();
    Console.WriteLine(result);
    

    (Note that this code does no error checking.)

    EDIT: It seems that you want to have an array of ints. In that case, you can do it like this (again, with no error checking):

    using System;
    using System.Linq;
    
    namespace Demo
    {
        internal class Program
        {
            private static void Main()
            {
                int n = int.Parse(Console.ReadLine());
                int[] arr = Console.ReadLine().Split(' ').Take(n).Select(int.Parse).ToArray();
                int sum = arr.Sum();
    
                Console.WriteLine("{0}", sum);
            }
        }
    }