moving from gitlab
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
#include <stdio.h> // output to terminal
|
||||
#include <stdlib.h> // has our atoi method
|
||||
|
||||
long factorial(int n);
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
|
||||
// get first to arguments passed
|
||||
// very first is name of program
|
||||
printf("argv[0]: %s\n", argv[0]);
|
||||
// argv[0] = ./nameofexecutable
|
||||
// argv[1] will be our value to caluclate factorial
|
||||
|
||||
if (argc < 2) {
|
||||
printf("error: value to calculate factorial is missing");
|
||||
printf("\tUsage: ./factorial 3\n\twhere 3 is the value to calculate\n");
|
||||
return -1;
|
||||
}
|
||||
// convert our char * to an int
|
||||
int n = atoi(argv[1]);
|
||||
|
||||
printf("Factorial of %d is %ld\n", n, factorial(n));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// use recursion first time through?
|
||||
// then maybe show a simple for loop
|
||||
long factorial(int n) {
|
||||
|
||||
// factorial is annotated as N!
|
||||
// example: 5! = 5 x 4 x 3 x 2 x 1
|
||||
// 0! = 1
|
||||
// so properties of math yada yada..
|
||||
// we can: 5! = 1 x 2 x 3 x 4 x 5
|
||||
// we can use a basic loop and go all the way up to n
|
||||
long answer = 1;
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// answer = answer * i;
|
||||
answer *= i;
|
||||
}
|
||||
return answer;
|
||||
|
||||
if (n == 1)
|
||||
return 1;
|
||||
return n * factorial(n - 1);
|
||||
}
|
||||
Reference in New Issue
Block a user