Reputation: 311
I'm begining with programming. I'm using javascript.
For practice, I print a triangle like this:
*
**
***
****
*****
but I want to print right to left, like this:
*
**
***
****
*****
So, with my noob knowledge, I wrote this code:
var line = '';
var size = 5;
for (var i = 0; i <= size; i++) {
for (var j = 0; j <= size; j++) {
if (j == size - i) {
line += '#';
if (i != 0) {
for (var k = j; k < size; k++) {
line += '#';
}
}
} else {
line += ' ';
}
}
line += '\n';
}
console.log(line);
It works! But I think it's awful.
Could someone give me some advice?
Thanks very much!
Upvotes: 0
Views: 1849
Reputation: 19
function staircase(n) {
// Write your code here
let output = ""
for (let i = 1; i <= n; i++) {
output += " ";
}
for (let i = 1; i <= n; i++) {
output = output.slice(1, output.length);
output += "#";
console.log(output)
}
}
Upvotes: 1
Reputation: 2466
You can try this one also
function print(n){
for (var i=1;i<=n;i++) {
var str = "";
for (var j=0;j<n;j++) {
str+= (j >= n-i)?"*":" "
}
console.log(str);
}}
print(9)
Upvotes: 1
Reputation: 8732
A little shorter:
var size = 5;
for (i=0;i<size;i++) {
var txt = ""
for (j=1;j<=size;j++) {
txt+=" *"[(j>=size-i)+0]
}
console.log(txt)
}
Upvotes: 1
Reputation: 1668
Please use this.
var N = 5;//based on your input
for (var i=0;i<N;i++) {
var str = "";
for (var j=0;j<N;j++) {
if (j >= N-i-1) {
str += "*";
} else {
str += " ";
}
}
console.log(str);
}
Upvotes: 0