ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Recursion in C

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='28' AND `tutorial_submenu`='1657' AND `tutorial_status`=1 LIMIT 1

Recursion in C

? Recursion in C

Recursion is when a function calls itself to solve a smaller part of the problem. It continues until it reaches a base case (the stopping condition).


? Basic Syntax

c

() { function(); // Recursive call}

To avoid infinite recursion, always define a base case!


? Example: Factorial Using Recursion

c

#include int factorial(int n) { () { int num = 5; printf("Factorial of %d is %d\n", num, factorial(num)); return 0;}

? Output:

csharp

Factorial of 5 is 120


? Key Concepts

  • Base case: Stops the recursion (e.g., if (n == 0)).

  • Recursive case: Function calls itself (e.g., n * factorial(n - 1)).


? Another Example: Fibonacci Series

c

int fibonacci(int n) { if (n == 0) return 0; if (n == 1) return 1; return fibonacci(n - 1) + fibonacci(n - 2);}


?? When to Avoid Recursion

  • Recursion can lead to stack overflow for deep recursion.

  • Iteration is often more efficient in C.


? Tip:

Use recursion when a problem can be broken into smaller similar subproblems, like:

  • Factorial

  • Fibonacci

  • Tree traversal

  • Tower of Hanoi

  • Searching/sorting algorithms (quick sort, merge sort)

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql