Docsity

Recursion detailed notes, Study notes of C programming

Toggle sidebar
bg1
Notes Prepared By Ms. Aasiya Khatoon
Recursion in C
Recursion is a process in which a function calls itself directly or indirectly to solve a problem.
It provides an elegant way to solve problems that can be divided into smaller, similar sub-
problems.
Characteristics of Recursion
1. Base Case: Terminates the recursion to avoid infinite calls.
2. Recursive Case: Breaks the problem into smaller sub-problems and calls itself.
Advantages
Simplifies complex problems.
Reduces the need for complex loops.
Disadvantages
Uses more memory (stack space) compared to iterative solutions.
May lead to stack overflow if not implemented correctly.
1. Factorial of a Number (Recursive)
The factorial of a number nn is defined as:
n! =n×(n−1) ×(n−2) ⋯×1
For n=0, 0! =1
Example
#include <stdio.h>
// Recursive function to find factorial
int factorial (int n) {
if (n == 0) {
return 1; // Base case
}
return n * factorial (n - 1); // Recursive case
}
pf3

Partial preview of the text

Download Recursion detailed notes and more Study notes C programming in PDF only on Docsity!

Recursion in C

Recursion is a process in which a function calls itself directly or indirectly to solve a problem. It provides an elegant way to solve problems that can be divided into smaller, similar sub- problems. Characteristics of Recursion

  1. Base Case: Terminates the recursion to avoid infinite calls.
  2. Recursive Case: Breaks the problem into smaller sub-problems and calls itself. Advantages  Simplifies complex problems.  Reduces the need for complex loops. Disadvantages  Uses more memory (stack space) compared to iterative solutions.  May lead to stack overflow if not implemented correctly. 1. Factorial of a Number (Recursive) The factorial of a number n n is defined as: n! =n×(n−1) ×(n−2) ⋯× 1 For n=0, 0! = Example #include <stdio.h> // Recursive function to find factorial int factorial (int n) { if (n == 0) { return 1; // Base case } return n * factorial (n - 1); // Recursive case }

int main () { int num; printf("Enter a number: "); scanf("%d", &num); printf("Factorial of %d is %d\n", num, factorial(num)); return 0; }

2. Fibonacci Series (Recursive) The Fibonacci series is defined as: F(n)=F(n−1) +F(n−2) With base cases: F (0) =0, F (1) = 1 Example #include <stdio.h> // Recursive function to find Fibonacci number int fibonacci(int n) { if (n == 0) return 0; // Base case if (n == 1) return 1; // Base case return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case } int main() { int n, i; printf("Enter the number of terms: "); scanf("%d", &n); printf("Fibonacci series: "); for (i = 0; i < n; i++) {