Home > Back-end >  How to make downward triangke looping from number 5 to 1
How to make downward triangke looping from number 5 to 1

Time:11-30

How to make downward triangle from 5 to 1

function segitiga(baris) {
  let pola = '';
  for (let i = 1; i <= baris; i  ) {
    for (let j = baris; j >= i; j--) {
      pola  = i;
    }
    pola  = '\n';
  } return pola;
} console.log(segitiga(5));

Output

11111
2222
333
44
5

I want the output can be like this

Output:

55555
4444
333
22
1

CodePudding user response:

You can change the calculation for pola in the inner loop and tweak the two loops for easier understanding like so:

function segitiga(baris) {
    let pola = "";
    for (let i = 0; i < baris; i  ) {
        for (let j = baris; j > i; j--) {
            pola  = baris - i;
        }
        pola  = "\n";
    }
    return pola;
}

You can also try an easier approach using javascript array methods like so:

const segitiga = (baris = 1) => {
    let current = baris;
    return new Array(baris)
        .fill(null)
        .map((_, idx) => new Array(current--).fill(baris - idx).join(""))
        .join("\n");
};

CodePudding user response:

I think you want your outer loop to count down from baris to one, so it needs to start at baris and then reduce by one each iteration until it reaches one. Your inner loop needs to loop i times, so you should be able to use a fairly basic for loop to account for that.

function segitiga(baris) {
  let pola = '';
  // start i at baris, carry on while i >= 1, reduce i by 1 each iteration
  for (let i = baris; i >= 1; i--) {
    // loop i times
    for (let j = 0; j < i; j  ) {
      pola  = i;
    }
    pola  = '\n';
  }
  return pola;
}

console.log(segitiga(5));

Included below is a version using the String repeat method, in case it's interesting.

const segitiga2 = (baris) =>
  Array.from({ length: baris }, (_, i) => ((baris - i)   '').repeat(baris - i))
    .join("\n");

console.log(segitiga2(5));

  • Related