factv2
This commit is contained in:
Binary file not shown.
@@ -0,0 +1,46 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
/*
|
||||||
|
* factorials
|
||||||
|
*
|
||||||
|
* in both for loop, as well as recursive
|
||||||
|
* factorial: voor int i, vermenigvuldig dan elke i to je bij 1 komt (uit gaande van positive ints)
|
||||||
|
*
|
||||||
|
* dus, f(3)=3*2*1 = 6 ; f(4)=4*3*2*1=24 ; f(a)=no ; f(-2)= no ; f(2.1) = no
|
||||||
|
*
|
||||||
|
* will use 2 functions:
|
||||||
|
* recfac using recursion
|
||||||
|
* itfac using iteration
|
||||||
|
*
|
||||||
|
* should probably figure out how to test this? maybe a dumb K:V?
|
||||||
|
* * */
|
||||||
|
|
||||||
|
int recfact(int input){
|
||||||
|
int fac = 1;
|
||||||
|
if (input==1) {
|
||||||
|
return fac;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
fac *= input * recfact(input-1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int itfact(int input){
|
||||||
|
int sum = 1;
|
||||||
|
for (int i = 1; i <= input; i++) {
|
||||||
|
sum *= i;
|
||||||
|
}
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
|
||||||
|
int input = 5;
|
||||||
|
|
||||||
|
//recfact(input);
|
||||||
|
//itfact(input);
|
||||||
|
printf("%d\n", recfact(input));
|
||||||
|
printf("%d\n", itfact(input));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user