Reputation: 13
I have a problem with my exercise. I have to draw something like this: https://screenshots.firefox.com/3qaHB7dcr3n610hi/jsbin.com
And this is my code
var empty = "";
for(var i=0; i < 5; i++) {
empty += "*";
console.log(empty)
}
but with this code I can only make this:
*
**
***
****
*****
I have no idea how to reverse this loop to start it from top from 5 stars, i tried something like this:
var empty = "";
for (i = 5; i <= 0;i--) {
empty+="*";
console.log(empty);
}
But doesn't work. Anybody know how to do this? I will be grateful :)
Upvotes: 1
Views: 59
Reputation: 418
Just in case you need a nested for loop. (As some exercises sometimes do)
var k = 0;
for(var i = 1; i < 12; i++){
var stx = "";
for(var j = k; j < i; j++){
stx += "*";
}
if(i > 5) k += 2
if(i == 6) continue
console.log(stx);
}
Upvotes: 0
Reputation: 33726
slice
in descending direction.var empty = "";
var i = 0;
// Build the first part
for (; i < 5; i++) {
empty += "*";
console.log(empty)
}
// Here i = 5, so this is the initialization for the following loop.
// Loop in descending direction using the function slice.
for (; i > 0; i--) {
console.log(empty.slice(0, i))
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2
Reputation: 63524
Instead of a for/loop
you could use a while
loop to change the direction:
let stars = 0;
let count = 0;
while (count < 9) {
if (count < 5) stars++;
if (count >= 5) stars--;
const line = Array(stars).fill('*').join('');
console.log(line);
count++;
}
Upvotes: 0
Reputation: 5041
Your condition was wrong. Check this.
for(let i = 1; i <= 5; i++) {
console.log('\"' + '*'.repeat(i) + '\"');
}
for(let i = 5; i > 0; i--) {
console.log('\"' + '*'.repeat(i) + '\"');
}
Upvotes: 1