02-integer_overflow.c 621 Bytes
Newer Older
Xavier Besseron's avatar
PS 2021  
Xavier Besseron committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
#include <stdlib.h>

// This program computes factorial.
//
// Examples of usage:
//
//   ./02-integer_overflow 4
//   ./02-integer_overflow 10
//   ./02-integer_overflow 20
//


int factorial(int n)
{
  int result = 1;
  int i;
  for ( i = 2 ; i <= n ; i++ )
  {
    result *= i;
  }
  return result;
}

int main(int argc, char** argv)
{
  // check number of parameters
  if ( argc != 2)
  {
    printf("Error: exactly one parameter is required!\n");
    return 1;
  }

  // get first parameter
  int n = atoi(argv[1]);
  int fact = factorial(n);
  printf(" fact(%i) = %i\n", n, fact);

  return 0;
}