title: What is the best way to ensure a user only enters natural numbers?
body: <p>Just started learning C, and it would be great if you could help me with the following:</p>
  
  <p>I just wrote a program that calculates the factorial of a natural number entered by the user. If the number is negative or a character, it should notify the user with the message <code>You have not entered a natural number.</code>. This message comes from the function <code>check_if_valid_value</code>.</p>
  
  <p>So far, it displays that message when entering characters, but doesn't seem to work with negative values. I thought casting the variable as <code>long long unsigned</code> would do the trick, but doesn't seem to be the case. The thing is the <code>scanf()</code> function returns a <code>0</code> so not sure why the program doesn't run the function <code>check_if_valid_value</code> so that it returns the message:<code>You have not entered a natural number.</code></p>
  
  <p>I am looking forward to reading any suggestions to improve this piece of code!</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  void check_if_valid_value(int value_entered)
  {
          if (value_entered != 1) 
          {
                  printf("You have not entered a natural number.\n");
                  exit(1);
          }
  }          
  
  void do_the_factorial(int p)
  {  
          int i;
          unsigned long long int factorial=1;
  
          for (i = 1; i &lt;= p; ++i)
          {
                  factorial=factorial*i;
                  printf("%llu\n", factorial);
          }
  }
  
  
  int main(void)
  {
          int value_entered, p;
  
          printf("Enter a natural number:");
  
          value_entered=scanf("%llu",&amp;p);
  
          check_if_valid_value(value_entered);
  
          do_the_factorial(p);
  
          return 0;
  }
  </code></pre>