0

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);

3
  • 2
    swap console.log and a calls. Or don't mutate a (a(n - 1)). Commented Mar 19, 2020 at 18:27
  • I have swapped a and console.log but it prints 10 to 2 now. Commented Mar 19, 2020 at 18:30
  • Before return on 1 console it again. Commented Mar 19, 2020 at 18:32

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, But how can i do it for 1 to 10.
Can you please guide me what is the difference between my above programme and your given programme.
But Why its start from 2 and print till 10 if i use n-1 instead of --n;
But why the output is different, with n-1 and --n, as we can see both these are same.
it is not the same. by using n - 1, n keeps the old value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.