Two dimensional array to find the sum of adjacent numbers

using System;

namespace SumRowColumn2dArray
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] array = new int[,]
            {
                {1,2,3,4},
                {4,5,6,1},
                {7,8,9,0},
            };
            Console.WriteLine(SumOfAdjacent(array, 0));
            Console.Read();
        }

        public static int SumOfAdjacent(int[,] array, int element)
        {
            int total = 0;
            int x = 0, y = 0;
            bool isNotFound = true;
            for (int i = 0; i < array.GetLength(0); i++) // row
            {
                for (int j = 0; j < array.GetLength(1); j++) // column
                {
                    if (array[i, j] == element && isNotFound)
                    {
                        isNotFound = false;
                        x = i;
                        y = j;
                    }
                }
            }

            if (checkIndexOutOfRange(array, x - 1, y - 1)) total += array[x - 1, y - 1];
            if (checkIndexOutOfRange(array, x - 1, y)) total += array[x - 1, y];
            if (checkIndexOutOfRange(array, x - 1, y + 1)) total += array[x - 1, y + 1];
            if (checkIndexOutOfRange(array, x, y - 1)) total += array[x, y - 1];
            if (checkIndexOutOfRange(array, x, y + 1)) total += array[x, y + 1];
            if (checkIndexOutOfRange(array, x + 1, y - 1)) total += array[x + 1, y - 1];
            if (checkIndexOutOfRange(array, x + 1, y)) total += array[x + 1, y];
            if (checkIndexOutOfRange(array, x + 1, y + 1)) total += array[x + 1, y + 1];
            return total;
        }

        public static bool checkIndexOutOfRange(int[,] array, int x, int y)
        {
            if ((x < array.GetLength(0) || x > array.GetLength(0)) && (y < array.GetLength(1) || y > array.GetLength(1)))
            {
                if (x < 0 || y < 0)
                {
                    return false;
                }else
                {
                    return true;
                }
            }
            return false;
        }
    }
}

results matching ""

    No results matching ""