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.

  • Does this answer your question? [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – jazb Sep 30 '21 at 06:57
  • @Jazb I still don't know how to add them so no. –  Sep 30 '21 at 06:58
  • find the sum of each array, then add the two sums... – jazb Sep 30 '21 at 06:59

1 Answers1

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];
}
fubo
  • 44,811
  • 17
  • 103
  • 137
  • "Sum()" just gets underlined. –  Sep 30 '21 at 07:00
  • @Connor add `using System.Linq;` – fubo Sep 30 '21 at 07:01
  • 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. –  Sep 30 '21 at 07:03
  • @Connor side note, you have a bug in your code, the second `for` loop uses `numarr1` instead of `numarr2` – fubo Sep 30 '21 at 07:04