Home > Back-end >  C# Adding the sum of 2 Arrays
C# Adding the sum of 2 Arrays

Time:10-01

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.

CodePudding user response:

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];
}
  • Related