Home > Software design >  Qn-print and write all array element using recursion in JavaScript cuz i'm new to the concept o
Qn-print and write all array element using recursion in JavaScript cuz i'm new to the concept o

Time:11-29

Here is my code and I know there is some mistake in my code but I'm new to the concept of recursion. I think there is a problem cuz I tried to implement the same code as the C language. I want my answer to read and print array by using recursion And I tried to convert the c code into javascript, c code into javascript and lastly in python code into javascript.

var a = [1, 2, 3];
var l = a.length;
var num = 0;

function printArr(a, i, l){
  for(var i=0; i<l; i  ){
    num = a[i];
  }
  if(i>=l){
    return 0;
    printArr(a, i 1, l);  //<I think in this section I'm having a problem.>
  }
}

printArr(a, 0, l); 
console.log(num);   

CodePudding user response:

No need for that for loop.

Your printArr call should be outside if statement.

var a = [1, 2, 3];
var l = a.length;
//var num = 0; // not needed

function printArr(a, i, l) {
  // Base condition - to break out of recursion
  // check if index is out of array bounds, if yes return
  if (i >= l) {
    return;
  }

  // if not, print the array element at that index
  console.log(a[i]);

  // call the recursive function with next consecutive index
  printArr(a, i   1, l);
}

printArr(a, 0, l);  
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related