DEV Community

Abdullah-fy
Abdullah-fy

Posted on

recursion in c

**first what is recursion?
it is a programming technique that you use to make the function call itself, you split a big problem to small ones.

it solve the problem that you can not solve with loops specially in array and binary tree statements and others.

it widely use in algorithms and data structures.

how can i write it?

easier to get a simple example

void welcome()
{
printf("hello programmser");

     welcome(); // notice its the name of your function but we have a problem here we need a base case i will explain down
Enter fullscreen mode Exit fullscreen mode

}

now when we call welcome function , it will print hello programmer then call itself again and print hello programmer and again and so on.

*so we hava a problem here which is ,it can not stop , so we must put something to stop it or we will be in infinite loop and cause code crash *

here is it called base case which it is a statement when it is right the function will stop

*so in recursion we have *
1- base case: a statement makes code stop
1- general case: which is the code which will repeat

examples:-

example (1):-

i want to find the factorial of 5 (5!)

first we should find the base case

5! = 5 * 4!
and 4! = 4 * 3!
and 3! = 3 * 2!
and 2! = 2 * 1!
and 1! = 1 // here is the base case
so the code will be

Image description

and when we run the code

Image description

example (2) :-
about fobonacci series

if you do not know it, every number is the sum of the last two number before it
like this

the number 0 1 1 2 3 5 8 13 .........
its index 0 1 2 3 4 5 6 7 .......

Image description

if you looked at this image you will find index number 6 equal index number 5 plus index number 4 and so on

at the end you will find n == 1 or n == 0 you can use any of them as a base case

so lets try to code this series

Image description

Image description

example (3):-

make a function like puts (print string followed by a new line)

Image description

Image description

example (4):-

print string in reverse.

remember the last index in any array is always '\0' , so it is our base case

Image description

this _print_rev_recursion(a + 1); use to not print '\0'

and putchar(*a); use to print for left because when i call this function i am at the end of it

Image description

hope it helps.
good luck and keep going.

Top comments (0)