in JavaScript by
Q:
What is recursion in a programming language?

1 Answer

0 votes
by
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

Related questions

+1 vote
asked Feb 10, 2020 in R Language by rahuljain1
0 votes
asked Mar 17, 2020 in C Plus Plus by SakshiSharma
...