What is recursion in a programming language?

Q:
What is recursion in a programming language?

1 Answer

0 votes
Recursion is a technique to iterate over an operation by having a function call itself repeatedly until it arrives at a result.

function add(number) {

if (number <= 0) {

return 0;

} else {

return number + add(number - 1);

}

}

add(3) => 3 + add(2)

3 + 2 + add(1)

3 + 2 + 1 + add(0)

3 + 2 + 1 + 0 = 6

Example of a recursive function:

The following function calculates the sum of all the elements in an array by using recursion:

function computeSum(arr){

if(arr.length === 1){

return arr[0];

}

else{

return arr.pop() + computeSum(arr);

}

}

computeSum([7, 8, 9, 99]); // Returns 123
Click here to read more about JavaScript
Click here to read more about Insurance

0 votes
0 votes
0 votes
0 votes
+1 vote
+1 vote
0 votes
0 votes
0 votes
+3 votes
0 votes
0 votes
0 votes
+4 votes
0 votes
0 votes
+2 votes
0 votes
0 votes
+1 vote
0 votes
+1 vote
0 votes
0 votes
0 votes
0 votes
0 votes
0 votes