1

I want to add the sum of two arrays that the user filled himself together in a variable or in a third array and then print it out. This is what I am stuck with:

Console.Write("How many numbers do you want to add: ");
        int howmany = Convert.ToInt32(Console.ReadLine());
       
        int[] numarr1 = new int[howmany];
        int[] numarr2 = new int[howmany];
        int[] res = new int[1];

        for (int i = 0; i < numarr1.Length; i++)
        {
            Console.Write("Input a first number: ");
            int a = Convert.ToInt32(Console.ReadLine());

            numarr1[i] = a;            
        }
        for(int b = 0; b < numarr2.Length; b++)
        {
            Console.Write("Input a second number: ");
            int a = Convert.ToInt32(Console.ReadLine());

            numarr1[b] = a;
        }
        int result = numarr1 + numarr2;

Everything works except the last line where I try to add them. On the Internet, I was searching for "How to add the sum of two arrays but I didn't really find anything that really solves my problem.

3
  • Does this answer your question? How to find the sum of an array of numbers Commented Sep 30, 2021 at 6:57
  • @Jazb I still don't know how to add them so no. Commented Sep 30, 2021 at 6:58
  • find the sum of each array, then add the two sums... Commented Sep 30, 2021 at 6:59

1 Answer 1

2

how about using Linq.Sum()

int result = numarr1.Sum() + numarr2.Sum();

or just add the values during iteration

Console.Write("How many numbers do you want to add: ");
int howmany = Convert.ToInt32(Console.ReadLine());
int[] numarr1 = new int[howmany];
int[] numarr2 = new int[howmany];
int[] res = new int[1];
int result = 0; // result here
for (int i = 0; i < numarr1.Length; i++)
{
    Console.Write("Input a first number: ");
    numarr1[i] = Convert.ToInt32(Console.ReadLine());
    result += numarr1[i];
}
for (int b = 0; b < numarr2.Length; b++)
{
    Console.Write("Input a second number: ");
    numarr2[b] = Convert.ToInt32(Console.ReadLine());
    result += numarr2[b];
}
Sign up to request clarification or add additional context in comments.

4 Comments

"Sum()" just gets underlined.
@Connor add using System.Linq;
The result is five when I enter in that I want to add 2 numbers so the first 2 numbers were 2 and 3 and the second 2 numbers were 2 and 3 too, but the result is 5, it must be 10.
@Connor side note, you have a bug in your code, the second for loop uses numarr1 instead of numarr2

Your Answer

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