Advertisement
nKolchakoV

Untitled

Dec 30th, 2013
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.21 KB | None | 0 0
  1. using System;
  2.  
  3.     class Program
  4.     {
  5.         static void Main(string[] args)
  6.         {
  7.             int n = int.Parse(Console.ReadLine());
  8.             int maxNum = int.MinValue;
  9.            
  10.             int[] array = new int[n];
  11.             for (int i = 0; i < array.Length; i++)
  12.             {
  13.                 Console.Write("array[{0}] = ",i);
  14.                 array[i] = int.Parse(Console.ReadLine());
  15.             }
  16.             Console.Write("Enter K = ");
  17.             int k = int.Parse(Console.ReadLine());
  18.             Array.Sort(array);
  19.             int index = Array.BinarySearch(array,k);
  20.  
  21.  
  22.             for (int i = 0; i < n; i++)
  23.             {
  24.                 if (array[i] == k)
  25.                 {
  26.                     Console.WriteLine(k);
  27.                     return; //if K exists in the array the program ends.
  28.                 }
  29.             }
  30.             for (int i = 0; i < n; i++) //If K doesnt exist we search the last number in the array which is < K.
  31.             {
  32.                 if (array[i] < k)
  33.                 {
  34.                     maxNum = array[i];
  35.                 }
  36.             }
  37.             Console.WriteLine("K wasn't found! \nPrevious num is: {0}",maxNum);
  38.  
  39.         }
  40.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement