0

I have been trying to solve printing down left side star(*) pattern in Javascript using recursion, i think my logic is correct but my syntax and concept might be wrong

// * * * * *
// * * * *
// * * *
// * *
// *

This is my code solution so far

var triangle = function (row, col) {
    if(row == 0){
        return
    }
    if(col < row){
        console.log("*")
        triangle(row, col + 1)
    }else{
        console.log("\n")
        triangle(row - 1, 0)
    }
}
triangle(4, 0)

output

*
*
*
*


*
*
*


*
*


*

But i want the output to be

* * * * *
* * * *
* * *
* *
*
1

2 Answers 2

1

console.log() closes the output stream automatically, the "line break" is because it is the next output session. You will see its true form if you use document.write.

var triangle = function (row, col) {
    if(row == 0){
        return
    }
    if(col < row){
        document.write("*")
        triangle(row, col + 1)
    }else{
        document.write("<br/>")
        triangle(row - 1, 0)
    }
}
triangle(4, 0)

But if you insist to use console.log(), some modification must be made:

var triangle = function (row, col, stream = '') {
    if(row == 0){
        return
    }
    if(col < row){
        stream += '*'
        triangle(row, col + 1, stream)
    }else{
        console.log(stream)
        stream = ''
        triangle(row - 1, 0, stream)
    }
}
triangle(4, 0)

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

1 Comment

Thanks man..... I think I would go with the second solution, the first solution return an error when run in VS code "ReferenceError: document is not defined" since i am not running it on HTML environment
0

check this solution

 function triangle(row){
        var print="";
        if(row==0){
            return;
        }
        for(var i=0;i<row;i++){
            print+="* "
        }
        console.log(print);
        triangle(row-1);
        
    }
    triangle(5);

1 Comment

Thanks man....I appreciate, this is cleaner but i think running it on for loop would increase it complexity(i might be wrong though)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.