Find two numbers in an array whose sum equals a given value

using System;

using System.Collections.Generic;

using System.Text;

using System.Text.RegularExpressions;

using System.IO;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] intArray = { 1, 2, 3, 4, 5, 6 };

            Console.WriteLine(Check(intArray, 10));

        }

        public static bool Check(int[] intArray, int num)

        {

            Array.Sort(intArray);

            int start = 0;

            int end = intArray.Length – 1;

            int sum = 0;

            while (start != end)

            {

                sum = intArray[start] + intArray[end];

                if (sum < num)

                {

                    start++;

                }

                else if (sum > num)

                {

                    end–;

                }

                else

                {

                    Console.WriteLine("Num1 = " + intArray[start]);

                    Console.WriteLine("Num2 = " + intArray[end]);

                    Console.WriteLine("Sum  = " + num);

                    start = end;

                    break;

                }

            }

            if (sum == num)

            {

                return true;

            }

            else

            {

                return false;

            }

        }

    }

}

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s