Sum of all integers within a List<int>

Asked

Viewed 112 times

2

I have a way:

public static int soma(params int[] n)
        {
            int resultado = 0;

            for (int i = 0; i < n.Length; i++)
            {
                resultado += n[i];
            }

            return resultado;
        }

On my console:

List<int> numeros = new List<int>();

Console.WriteLine("Digite um numero");
numeros.Add(int.Parse((Console.ReadLine())));

resultado = soma(numeros); //Gera erro de conversão de list Generics para int

I’m wondering how to pass a list of entire parameters that the user types to the method. And also how you let the user stop typing to make the sum. Ex: it goes typing [1 2 3 4 5 6 8 9] and wants to stop and add, I’m not knowing the command to interrupt.

1 answer

2


inside the sum function, meta to enter a variable of type List, and just exchange this 'for' for a 'foreach', it will be like this:

public static int soma(List<int> nomedalista){ int resultado = 0; foreach(int x in nomedalista){ resultado+=x; } return resultado; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.