Program in C# to count odd elements of a 2D array

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 229
Suppose we have a 2D array

{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
}


We need to find the count of odd elements of the 2D array. The below program will do so

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{

int oddCounter=0;
int row = 4;
int col = 4;
int[,] matrix = new int[4, 4] {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if (matrix[i, j] % 2 != 0)
oddCounter++;
}

}
Console.Write("Number of Odd Elements in the matrix : " + oddCounter);
Console.ReadKey();

}
}
}

Result
--------
Number of Odd Elements in the matrix : 8

Comments or Responses

Login to post response