.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Post New Resource Bookmark and Share   

Find middle number in array

Posted By:satyapriyanayak       Posted Date: March 01, 2014    Points: 40    Category:    URL: http://www.dotnetspark.com  

In this Code Snippets we will know how to Find middle number in array.
 

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

namespace ConsoleApplication1
{
    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];
        }
        
    }
}


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend