Sabtu, 17 Oktober 2015

How Recursion Works with example in C

Recursion is a process that calls the process back. Recursion in C language functions are realized in the form of one or more instructions are dialing instructions to call a function that returns either directly or indirectly. Function which is called the recursive function. I use software C Compiler Dev C++
Example of recursion in C Programming

Write a C program to find sum of first n natural numbers using recursion. Example :

















Output :


in the program c on top, sum() function is invoked from the same function. If n is not equal to 0 then, the function calls itself passing argument 1 less than the previous argument it was called with. Suppose, n is 5 initially. Then, during next function calls, 4 is passed to a function and the value of argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is returned which is the sum numbers from 5 to 1.
The following explanation above recursion :

sum(10)
=10+sum(9)
=10+9+sum(8)
=10+9+8+sum(7)
=10+9+8+7+sum(6)
=10+9+8+7+6+sum(5)
=10+9+8+7+6+5+sum(4)
=10+9+8+7+6+5+4+sum(3)
=10+9+8+7+6+5+4+3+sum(2)
=10+9+8+7+6+5+4+3+2+sum(1)
=10+9+8+7+6+5+4+3+2+1+0
=10+9+8+7+6+5+4+3+2+1
=10+9+8+7+6+5+4+3+3
=10+9+8+7+6+5+4+6
=10+9+8+7+6+5+10
=10+9+8+7+6+15
=10+9+8+7+21
=10+9+8+28
=10+9+36
=10+45
=55
   
Every recursive function must be provided with a way to end the recursion. In this example when, n is equal to 0, there is no recursive call and recursion ends.

1 komentar:

  1. Thanks a lot for sharing. Private Tutor Tampa Will check back later for more of your articles.

    BalasHapus