0
What is the advantage of using recursion?
When I was doing the quiz on the recursion of functions, the example was a factoring function with recursion of itself. But this code does the same and easier to write: int main() { int a=1; for (int x=1; x <=4; x++) { a=a*x; } cout<< a; } So when or in what situations is recursion better or even necessary? I would appreciate if there were code examples of it. Thanks
1 Resposta
+ 1
usually i think u can use loops or other methods instead of recursion but it can end up very complicated and hard to read later on
as an example - i am not going to put an entire code but consider making a code that can solve a Sudoku
lets say i have a function
int** solve_sudoku(int sudoku[9][9]);
that can solve a sudoku
i could have a very complicated code to solve it
or i could make it a bit more simple (to read) and for every number or every few numbers i manage to find in the sudoku i re-call this function (in recursion) as if i have a new sudoku with a few more numbers in it
the inside of the func will look like:
int** solve_sudoku(int sudoku[9][9])
{
.
.
.
/* several functions to find numbers using several methods*/
.
.
.
/* once i found all the numbers i can in this function iteration i try again */
sudoku = solve_sudoku(sudoku); /*send a 'new' sudoku with the numbers we found*/
return sudoku;
}
again this is just a general idea of what it would look like
actualy coding it would take time (maybe i will try to write something like this sooner or later :) )