title: Insert element into array C
body: <p>I have an array of numbers that has been sorted in before, so there's no need to sort it, I need to insert an given value, named it <code>val</code>, at a valid position in my array.</p>
  
  <p>My program works for a given value that is smaller than the last one, but for the case where the value is bigger than the last one, my program just doesn't want to insert the value.</p>
  
  <p>For example, for the array <code>{1, 2, 3, 4, 6}</code> and the value <code>5</code>, the array should be <code>{1, 2, 3, 4, 5, 6}</code>, but for the value <code>7</code> my array is looking like <code>{1, 2, 7, 4, 6, 0}</code>.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  void insert(int val, int *n, int v[])
  {
      int index;
      index = n - 1;
      if (n == 0)
      {
          v[0] = val; // check if array is empty
          n = n + 1; // v[0] becomes the given value
      }              // increase size of array
      if (val &gt; v[index])
      {
          v[index+1] = val; // given value is bigger than the last value in array
          n = n + 1; // increase size
      }
      else
      {
          while (index &gt;= 0 &amp;&amp; v[index] &gt; val)
          {
              v[index+1] = v[index]; //shift items to the right
              index--;
          }
  
          v[index + 1] = val; //after moving elements to the right
          n = n + 1;   // i set the value to the valid position
      }
  }
  
  void display(int n, int v[])
  {
      int i;
      for (i = 0;i &lt; n; i++)
          printf("%d ", v[i]);
  }
  
  int main(void)
  {
      int v[10] = { 12, 23, 34, 41, 69, 71, 81, 91, 100 };
      int n;
      n = 9; // size of array
      insert(101,n,v); // 101 is given value to insert
      display(n,v);
      return 0;
  }
  </code></pre>