0% found this document useful (0 votes)
15 views7 pages

Understanding Recursion in C Programming

Recursion is a programming technique where a function calls itself until a base case is met, allowing for elegant solutions to problems like factorials and Fibonacci sequences. It involves a base case to stop recursion and a recursive case to continue calling the function with smaller inputs. While recursion simplifies code for certain problems, it can lead to slower performance and increased memory usage due to multiple function calls.

Uploaded by

nsdhanyasai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views7 pages

Understanding Recursion in C Programming

Recursion is a programming technique where a function calls itself until a base case is met, allowing for elegant solutions to problems like factorials and Fibonacci sequences. It involves a base case to stop recursion and a recursive case to continue calling the function with smaller inputs. While recursion simplifies code for certain problems, it can lead to slower performance and increased memory usage due to multiple function calls.

Uploaded by

nsdhanyasai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

WHAT IS RECURSION

Recursion means a function calling itself until a stopping condition is reached.


A recursive function has:
1. Base Case → When to stop calling itself.
2. Recursive Case → The function calls itself with smaller input.
EXAMPLE 1: Printing Levels (Recursion Going Down)
#include <stdio.h>
void rec(int n)
{
if (n == 6) // stop at 6
return;
printf("Level %d\n", n);
rec(n + 1); // call itself with bigger number
}
int main()
{
rec(1);
return 0;
}
Output
Level 1
Level 2
Level 3
Level 4
Level 5
Shows how recursion goes deeper one step at a time.
EXAMPLE 2: Recursion Going Down and Up (Stack Example)
#include <stdio.h>
void f(int n)
{
printf("Pushed %d\n", n); // Going down
if (n > 1)
{
f(n - 1);
f(n - 1);
}
printf("Popped %d\n", n); // Coming back
}
int main()
{
f(3);
return 0;
}
Shows:
 When called → stack grows (pushed)
 When returning → stack shrinks (popped)
✔ Helps you understand what happens inside memory.

How Recursion Works:


Think of recursion like going down stairs:
1. Walk down until the last step (base case)
2. Then return back up (unwinding phase)
WHY USE RECURSION?
✔ Easy for tree-like problems
✔ Some tasks naturally fit recursion (factorial, power, fibonaccis, searching trees)
✔ Sometimes much shorter code

Problems with Recursion


 Slower (because many function calls)
 Uses more memory (every call uses stack)
 Too many calls → Stack Overflow
Stack Overflow:
If a function calls itself too many times and never reaches the stopping point → memory fills
→ program crashes.
Structure of Recursive Function
type function(parameters)
{
if (base case) // stop
return value;
return function(smaller_value); // recursive call
}
Example: Count Digits of a Number
#include <stdio.h>
int countDigits(int n)
{
// Base case: when n becomes 0
if (n == 0)
return 0;
// Recursive case: remove last digit and count +1
return 1 + countDigits(n / 10);
}
int main()
{
int num, digits;
printf("Enter a number: ");
scanf("%d", &num);
// Handle 0 separately because it has 1 digit
if (num == 0)
digits = 1;
else
{
// If negative, make it positive
if (num < 0)
num = -num;
digits = countDigits(num);
}
printf("Number of digits: %d\n", digits);
return 0;
}

 Breaks the number


 Removes one digit at a time
 Counts digits until none left

Tracing a recursive function in C means writing out each function call (with its
parameters) as it goes deeper, and then following the returns back out, just like tracking
stack frames.

Basic idea

 Each call to a recursive function creates a new “copy” of that function (an activation
record/stack frame) with its own parameters and local variables.

 Calls continue until the base condition is met; then execution returns step by step in
reverse order as each call finishes and its frame is popped from the stack.

Simple example pattern

Consider a typical recursive factorial-style function (prototype form only):

 Base case: if n=¿ 0 (or n=¿ 1), return 1.


 Recursive case: return n∗(n−1)!.

To trace a call like fact(3), you write:

1. Winding (calls going down):

 fact(3)

 fact(3) calls fact(2)

 fact(2) calls fact(1)

 fact(1) hits base case and returns 1.

2. Unwinding (returns coming back):

 fact(1) returns 1 to fact(2)

 fact(2) computes 2 * 1 = 2 and returns 2 to fact(3)

 fact(3) computes 3 * 2 = 6 and returns 6 to caller.

How to teach/trace on paper

When tracing any recursive function f(...):

1. Write each call with arguments when it is made (top to bottom), indenting each
deeper level.

2. Stop expanding when you reach the base case; write its return value.

3. Move upward, computing the return expression at each level using the value
returned from the deeper call.

What “recursive function in C” means


 A recursive function in C is defined so that its body contains at least one call to itself,
and it always includes a base case to stop further calls.

 It is widely used to implement mathematically recursive definitions, like n !, Fibonacci


sequence, or recursive sum/series directly from their math formulas.

Typical mathematical examples

Common mathematical recursive functions you implement in C are:

 Factorial: computes n ! using the relation n !=n ×(n−1)! with base case 0 !=1.

 Fibonacci: returns the n th term using F (n)=F (n−1)+ F (n−2) with base cases F (0)
and F (1) .
 Sum of first n natural numbers: uses S(n)=n+ S(n−1) with base case S(0)=0.

If you want, a stepwise trace for any one of these (with stack behavior and values at each
call/return) can be shown in detail.

Recursive functions in C can work very naturally with arrays and strings by passing pointers
(array names / char pointers) and indices as parameters, then moving those indices in each
recursive call.

Key ideas with parameters

 Arrays and strings in C are passed to functions as pointers (e.g., int arr[], char str[] or
char *str), so a recursive function usually also takes an index (or start/end indices) as
extra parameters.

 The base case is typically when the index reaches the array length or when the string
hits the '\0' terminator; the recursive case processes one element/character and calls
the function on the “rest”.

Example: array parameter (print elements)

Conceptual pattern (without copying from sources):

 Parameters: int arr[], int index, int n

 Base case: if index == n, stop.

 Recursive step: print arr[index], then call the same function with index + 1 until all
elements are processed.

This same pattern can be adapted to:

 Sum of array elements (return arr[index] + recursive_sum(arr, index+1, n)).

 Finding max/min, counting negatives/odds, computing mean, etc., all by advancing


the index recursively.

Example: string parameter (length / reverse)

For strings, treat them as char * or char str[]:

 Length: parameters could be (char str[], int i); base case when str[i] == '\0', otherwise
return 1 + length(str, i+1).

 Reverse/print in reverse: pass char *str; base case when *str == '\0'; recursive step
calls the function with str+1 first, then processes *str on the way back, effectively
reversing the order.

You might also like