#Creating a triangle with asterisks

22 messages · Page 1 of 1 (latest)

plucky oar
#

I'm trying to make a triangle out of asterisks, but my script is adding an extra new line.

How can I stop it from doing this?

#
*
**
***
****

its supposed to be like this

#

but it ends up like

*
**
***
****
line
lilac rapids
#

Is this running twice at some point?

#

maybe log before it

#

I'd guess your first for loop is running 1 more time than the nested one, mess with the variables a bit

plucky oar
#

its adding a new line at the end of the output

lilac rapids
#

can you paste the code

plucky oar
#
function drawTriangle(size){
    var i;
    var j;
    var result = "";
    for(i=1;i<size+1;i++){
        for(j=1;j<i+1;j++){
            //console.log(i +","+ j);
            result += "*";
            
        }
        //console.log("R: "+result);
        result += "\n";    
            
        
    }
console.log(result);
}
   
lilac rapids
#

at the end of every * loop you're doing a new line

#

So that includes the last one

#

Which means a new line at the end

plucky oar
#

how can i make it to where it does the new line each time except at the very end

#

is this where a if statement comes in handy

lilac rapids
#

I guess you can just if check i is size - 1

#

or something like that

#

or if it isn't*

#
      if(!(i == (size))) {
        result += "\n"; 
      }
#

Might be a better way to do it but yeah

plucky oar
#

ah okay, thanks