Reputation: 25
i'm still learning c# and hava a question about my code. In theory i should get the value of 60 returned, but for some reason it only returns 47. Any one got an idea why? I want to solve it using while-loops and if. So a Solution without using foreach is required.
Any Help would be much appreciated.
My Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace B7ArraysPart2
{
class Program
{
/// <summary>
/// Returns the sum of all elements in the given array
/// [TESTMETHOD]
/// </summary>
/// <param name="arr">Array to build the sum over</param>
/// <returns>Sum of all elements in the given array</returns>
public static int Sum(int[,] arr)
{
//get arr.Length of both dimensions
int length1d = arr.GetLength(0);
int length2d = arr.GetLength(1);
//set the individual variables to 0
int sum1d = 0;
int sum2d = 0;
int i = 0;
int i2 = 0;
int c = 0;
//Doing first Row
while (i < length1d)
{
int add = arr[0, i];
sum1d += add;
i++;
}
//Doing second to all rows
if (c < length2d)
{
c++;
i2 = 0;
while (i2 < length1d)
{
int add2 = arr[c, i2];
sum2d += add2;
i2++;
}
}
Console.WriteLine("{0}, {1}", sum1d, sum2d);
return sum1d+sum2d;
}
static void Main(string[] args)
{
int[,] myArr2D;
myArr2D = new int[3, 3];
myArr2D[0, 0] = 10;
myArr2D[0, 1] = 11;
myArr2D[0, 2] = 12;
myArr2D[2, 0] = 13;
myArr2D[1, 2] = 14;
//Console.WriteLine("{0}", myArr2D[2, 0]);
Console.WriteLine("{0}", Sum(myArr2D));
Console.ReadKey();
}
}
}
Upvotes: 1
Views: 333
Reputation: 19179
Just iterate over 2d array in normal way and sum values.
int sum = 0;
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
sum += arr[i, j];
}
}
return sum;
This can be easily converted to while loop.
int sum = 0;
int i = 0;
while (i < arr.GetLength(0))
{
int j = 0;
while (j < arr.GetLength(1))
{
sum += arr[i, j];
j += 1;
}
i += 1;
}
return sum;
Upvotes: 1
Reputation: 11
Maybe you could try something like this :
static void Main(string[] args)
{
int[,] myArr2D;
myArr2D = new int[3, 3];
myArr2D[0, 0] = 10;
myArr2D[0, 1] = 11;
myArr2D[0, 2] = 12;
myArr2D[2, 0] = 13;
myArr2D[1, 2] = 14;
int sum = myArr2D.Cast<int>().Sum();
Console.WriteLine(sum); // 60
Console.ReadKey();
}
Upvotes: 1