Find middle number in array

Satyapriyanayak
Posted by Satyapriyanayak under C# category on | Points: 40 | Views : 1132
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
int[] a1 = { 1, 2, 3, 4, 5 };
Console.WriteLine("The middle number is {0}", GetMiddleNumber(a1));
Console.ReadKey();
}
static int GetMiddleNumber(int[] a1)
{
// if length is odd, return middle numer
if (a1.Length % 2 == 1) return a1[a1.Length / 2];

// if length is even return the first of the two middle numbers
return a1[a1.Length / 2 - 1];
}

}
}

Comments or Responses

Login to post response