Add C example for recursion (#41)
This commit is contained in:
19
03_recursion/c/01_countdown.c
Normal file
19
03_recursion/c/01_countdown.c
Normal file
@@ -0,0 +1,19 @@
|
||||
#include <stdio.h>
|
||||
|
||||
void countdown(int i) {
|
||||
printf("%d\n", i);
|
||||
|
||||
// base case
|
||||
if (i <= 0)
|
||||
return;
|
||||
//recursive case
|
||||
else
|
||||
countdown(i - 1);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
|
||||
countdown(5);
|
||||
|
||||
return 0;
|
||||
}
|
||||
23
03_recursion/c/02_greet.c
Normal file
23
03_recursion/c/02_greet.c
Normal file
@@ -0,0 +1,23 @@
|
||||
#include <stdio.h>
|
||||
|
||||
void greet2(char *name) {
|
||||
printf("how are you, %s?\n", name);
|
||||
}
|
||||
|
||||
void bye() {
|
||||
printf("ok bye!\n");
|
||||
}
|
||||
|
||||
void greet(char *name) {
|
||||
printf("hello, %s!\n", name);
|
||||
greet2(name);
|
||||
printf("getting ready to say bye...\n");
|
||||
bye();
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
|
||||
greet("adit");
|
||||
|
||||
return 0;
|
||||
}
|
||||
15
03_recursion/c/03_factorial.c
Normal file
15
03_recursion/c/03_factorial.c
Normal file
@@ -0,0 +1,15 @@
|
||||
#include <stdio.h>
|
||||
|
||||
int fact(int x) {
|
||||
if (x == 1)
|
||||
return 1;
|
||||
else
|
||||
return x * fact(x - 1);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
|
||||
printf("%d", fact(5));
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user