Sunday, June 11, 2017

Easy solution for binary search.

 static void Main(string[] args)
        {
            int key, mid, high,count=0, low;
            bool flag = false;
            Console.WriteLine("Enter TheLength of Sorted Array:");
            int length = Convert.ToInt32(Console.ReadLine());
            int[] array = new int[length];
            Console.WriteLine("Enter The Element");
            for(int i=0;i<length;i++)
            {
               array[i]=Convert.ToInt32(Console.ReadLine());
            }
            Console.WriteLine("Enter The Key Element You Want to search");
            key = Convert.ToInt32(Console.ReadLine());
            low = 0;
            high = length-1;
            mid = (low + high) / 2;
            for (int k = 0; low <= high; k++)
            {
                count = count + 1;
                if (array[mid] == key)
                {
                    Console.WriteLine("Element You searched:{0}\n Total No. of loop {1}", array[mid],count);
                    flag = true;
                    break;
                }
                else if (key < array[mid])
                {
                    high = mid - 1;
                    mid = (low + high) / 2;
                }
                else
                {
                    low = mid + 1;
                    mid = (low + high) / 2;
                }
            }
            if (false)
            {
                Console.WriteLine("Doesnt Exist");
            }
            Console.ReadKey();
        }

Find the fibbonaci series .

  static void Main(string[] args)
        {
            int prev=0, next=1, sum=0;
            Console.WriteLine("Enter No. of terms you want  in Series");
            int n = Convert.ToInt32(Console.ReadLine());
            Console.Write(prev+" ");
            Console.Write(next);
            for(int i=0;i<n-1;i++)
            {
                sum = prev + next;
                prev = next;
                next = sum;
                Console.Write("  "+next);
            }
           
            Console.ReadLine();
        }