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();
}
}
}
//Doing second to all rows, you should usewhileinstead ofif(And ensure that you stay inside of the bounds)