0

I'm learning basics of Java Script. I want to print the following in the console:

*2345
**345
***45
****5
*****
*****
****5
***45
**345
*2345

I've already wrote the code: var x = 5; var line;

for(var i = 0; i<x; i=i+1){
    line = "";
    for(var j=0; j<x; j=j+1){
        if(j <= i){
            line = line + " * ";
        }
    }
    console.log(line);
}
for(var i = x; i>0; i--){
    line = "";
    for(var j=0; j<x; j=j+1){
        if(j <= i-1){
            line = line + " * ";
        }
    }
    console.log(line)
}

So the result is:

*
**
***
****
*****
*****
****
***
**
*

Could anybody help me to modify the loop? I've tried various things but it never works.

2
  • 2
    Looks like an assignment question! Commented Oct 11, 2015 at 11:03
  • 1
    What conditions does your assignment set? :) Commented Oct 11, 2015 at 11:14

3 Answers 3

2

You can use this for both the if conditions :

else {
line += j + 1;
}
Sign up to request clarification or add additional context in comments.

Comments

1

I would have done it like this:

    var numbers = [1,2,3,4,5],
    nLength = numbers.length,
    result = [],
    stringOf = function( value,times,str ) {

      if( 'undefined' === typeof str )
        str = '';

      if( times === 0 )
        return str;

      str += value;

      times--;

      return stringOf( value,times,str );

    },
    log = function( el ) { console.log( el ) };

for ( var i = 0; i < nLength; i++ ) {

  result[ i ] = stringOf( '*',i + 1 ) + numbers.slice( i + 1,nLength).join('');
  result[ i + nLength ] = stringOf( '*',nLength - i ) + numbers.slice( nLength - i,nLength).join('');

}

result.map( log );

Output:

*2345
**345
***45
****5
*****
*****
****5
***45
**345
*2345

Editing numbers array would change the output which will be in the same manner as specified.

Comments

1

var baseString = "12345";
var starStrings = [];

for(var i = 0; i < baseString.length; i++){
  starStrings.push("*".repeat(i + 1) + baseString.slice(i + 1));
}
starStrings = starStrings.concat(starStrings.slice().reverse());

starStrings.forEach(function(s){
  document.write(s + "<br />");  
});

Comments

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.