title: How do I find the largest value smaller than or equal to X and the smallest value greater than or equal to X?
body: <p>I am trying to use <code>lower_bound</code> and <code>upper_bound</code> functions from the <code>algorithm</code> library in C++ to find the following things:</p>
  
  <ul>
  <li>The <strong><em>largest value smaller than or equal</em></strong> to a number X.</li>
  <li>The <strong><em>smallest value greater than or equal</em></strong> to a number X.</li>
  </ul>
  
  <p>I wrote the following code: </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;algorithm&gt;
  
  int main() {
  
      using namespace std;
  
      int numElems;
      cin &gt;&gt; numElems;
  
      int ar[numElems];
      for (int i = 0; i &lt; numElems; ++i)
          cin &gt;&gt; ar[i];
      stable_sort(ar,ar+numElems);
  
      cout &lt;&lt; "Input number X to find the largest number samller than or equal to X\n";
      int X;
      cin &gt;&gt; X;
  
      int *iter = lower_bound(ar,ar+numElems,X);
      if (iter == ar+numElems)
          cout &lt;&lt; "Sorry, no such number exists\n";
      else if (*iter != X &amp;&amp; iter != ar)
          cout &lt;&lt; *(iter-1) &lt;&lt; endl;
      else 
          cout &lt;&lt; *iter &lt;&lt; endl;
  
      cout &lt;&lt; "Input number X to find the smallest number greater than or equal to X\n";
      cin &gt;&gt; X;
  
      int *iter2 = lower_bound(ar,ar+numElems,X);
      if (iter2 == ar+numElems)
          cout &lt;&lt; "Sorry, no such number exists\n";
      else
          cout &lt;&lt; *iter2 &lt;&lt; endl;
  
      return 0;   
  }
  </code></pre>
  
  <p>But for some random test cases it gives me wrong answer.</p>
  
  <p>Can anyone find the incorrect piece of code in my program?</p>