Ashish
Ashish

Reputation: 410

Problem in recursion programme to print numbers

I have problem in below programme, below programme print number from 1 to 9, but i want to print number 10 also, how can i do that?

function a(n){
    if(n == 1){
        return;
    }
    a(--n);
    console.log("hello world = ",n);    
}

a(10);

Upvotes: 0

Views: 51

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You need to switch the exit condition and call the function only if you have a number which is not zero.

function a(n) {
    if (n !== 1) a(n - 1);
    console.log("hello world =", n);
}

a(10);

What you have is

function a(n){
    if (n == 1) {                     // exit condition
        return;                       // end of function run
    }
    a(--n);                           // mutating variable
    console.log("hello world = ", n);
}

an exit condition which checks the value and ends the function. This prevents to print the last value.

Another problem is the cange of n by calling the function again. The later used variable dos not have the original value anymore.

By changing the exit function to a check if the function should be called again, as the opposite of exit, it allows to run for each wanted number and make an output.

If you just change the --n to n - 1, you need another output for 1.

function a(n){
    if (n == 1) {
        console.log("hello world = ", n); // add another output here for 1
        return;
    }
    a(n - 1);
    console.log("hello world = ", n);
}

a(10);

Upvotes: 3

Related Questions