0% found this document useful (0 votes)
3 views3 pages

Recursion Functions

Recursion is a programming technique where a function calls itself to solve problems by breaking them down into smaller sub-problems. It requires a base case to prevent infinite loops. An example provided demonstrates a recursive function to calculate the sum of numbers from n down to 1.

Uploaded by

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

Recursion Functions

Recursion is a programming technique where a function calls itself to solve problems by breaking them down into smaller sub-problems. It requires a base case to prevent infinite loops. An example provided demonstrates a recursive function to calculate the sum of numbers from n down to 1.

Uploaded by

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

Recursion

• Recursion is the ability of a function to call itself.


• It is often used to solve problems that can be divided
into smaller, similar sub-problems — for example:
factorial, sum of numbers, Fibonacci series, etc.

How Recursion Works


When a recursive function calls itself, it must have a
stopping condition, known as the base case, to prevent
it from repeating forever.
Example: Recursive Function to Add Numbers

This program calculates the sum of numbers from n down to 1

👉 (i.e. n + (n-1) + (n-2) + … + 2 + 1)

#include <stdio.h>

int add(int); // Function declaration

int main(void) {
int num, ans;
printf("Enter any number: ");
scanf("%d", &num);
ans = add(num);
printf("Answer = %d", ans);
return 0;
}
// Recursive function definition
int add(int n) {
if (n == 1)
return 1; // Base case: stop recursion
else
return n + add(n - 1); // Recursive call
}

OUTPUT:
If the user enters 4, then:
add(4) = 4 + add(3)
add(3) = 3 + add(2)
add(2) = 2 + add(1)
add(1) = 1(base case)

add(4) = 4 + 3 + 2 + 1 = 10

You might also like