i'm trying to make a right aligned triangle. I am able to make a left aligned triangle easily, but can't get the number of spaces to decrease with each additional row.
output should be:
#
##
###
####
#####
let levels = 8; let hash = ''; for (let i = 1; i <= levels; i++) { hash += '#'; console.log(hash) }
Instead of reusing the same string, consider generating each row with repeat()
and padStart()
:
function rightAlignedTriangle (levels) { for (let i = 1; i <= levels; i++) { const row = '#'.repeat(i).padStart(levels) console.log(row) } } rightAlignedTriangle(5)
To implement this using a nested loop instead of string methods, you can manually implement the above two methods as an inner loop on a variable string declared in the outer loop:
function rightAlignedTriangle (levels) { for (let i = 1; i <= levels; i++) { let row = '' for (let j = 0; j < levels; j++) { if (j < i) { row += '#' } // repeat(i) else { row = ' ' + row } // padStart(levels) } console.log(row) } } rightAlignedTriangle(5)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.