Recursive Function Exercises C Solutions
Recursive Function Exercises C Solutions
The stopping case (base case) is essential to prevent infinite recursion. It tells the
function when to stop calling itself. Without a base case, the program would run
indefinitely and cause a stack overflow.
#include <stdio.h>
void pattern(int n) {
if (n == 1) {
printf("1 ");
return;
}
pattern(n - 1);
printf("%d ", n);
pattern(n - 1);
}
int main() {
int n = 3;
pattern(n); // Output: 1 2 1 3 1 2 1
return 0;
}
#include <stdio.h>
int f(int n) {
if (n == 1)
return 1;
else
return 2 * f(n - 1);
}
int main() {
printf("%d\n", f(4)); // Output: 8
return 0;
}
Recursive method: Easier for problems like factorial, Fibonacci, tree traversal.
Non-recursive method: More efficient in memory and performance.
Preferable: Non-recursive, unless recursion is clearer.
Recursive Function Exercises - C Language Solutions
#include <stdio.h>
void printNumbers(int n) {
if (n < 0)
return;
printf("%d\n", n);
printNumbers(n - 1);
}
int main() {
printNumbers(5);
return 0;
}
6. Recursive function to reverse input and check for space (no arrays/strings).
#include <stdio.h>
int reverseAndCheckSpace() {
char ch = getchar();
if (ch == '\n')
return 0;
int hasSpace = reverseAndCheckSpace();
putchar(ch);
if (ch == ' ')
hasSpace = 1;
return hasSpace;
}
int main() {
printf("Enter text (press Enter to end):\n");
int hasSpace = reverseAndCheckSpace();
printf("\nContains space: %s\n", hasSpace ? "Yes" : "No");
return 0;
}
#include <stdio.h>
int main() {
int num = 7;
if (isPrime(num, 2))
printf("%d is prime\n", num);
else
printf("%d is not prime\n", num);
return 0;
}
#include <stdio.h>
int main() {
printf("Enter characters (space to stop):\n");
int depth = getDepthUntilSpace(0);
printf("Space found at depth: %d\n", depth);
return 0;
}