Recursion in programming is a technique used mainly in functional programming languages to break down a problem you have into smaller, identical sub-problems. Recursion simplifies the problem-solving process by allowing the solution to be expressed in terms of a smaller version of the same problem.
The main uses of recursion in programming include:
function fibRecursion(n) if n < 0 then error("Invalid number.") return 0 end if n <= 1 then return n else return fibRecursion(n-1) + fibRecursion(n-2) end end
We can see that when the number is less than 0, it will give us an error, when the number is less than 1 and greater than 0 it will return itself, if the number is greater than 1, it will return the sum of (n-1) and (n-2), we can call the function and it will give us the fibonacchi number in the n position
let's add a for loop that prints the numbers from 1 to 12
function fibRecursion(n) if n < 0 then error("Invalid number.") return 0 end if n <= 1 then return n else return fibRecursion(n-1) + fibRecursion(n-2) end end for i=1, 12 do print("fibonnaci number in the position ".. i.. ": ".. fibRecursion(i)) end
The fibonacci numbers from 1 to 12 are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
when we run the program, we can see that it indeed, gives us those numbers!