1

Using a FOR loop to add and output numbers is easy. But how do you add and output additional characters?

For example the following simple program outputs the numbers 1 through 7 to the console.

for (var count = 0; count < 7; count++) {
    console.log(count + 1);
}

But what if instead of numbers I needed to add additional characters or symbols each loop? For example how would someone output characters to the console like this?

A

AA

AAA

AAAA

AAAAA

AAAAAA

AAAAAAA

I'm sure the answer is straightforward but I don't know how to approach this type of problem.

DR01D
  • 1,325
  • 15
  • 32
  • 1
    Have another for loop inside that loops from 1 to count, and output a character at each iteration. After the inner for loop emit the line break – Dijkgraaf Jun 22 '17 at 18:56
  • 2
    `var txt = ""; for(var count = 0; count < 7; count++) { console.log(txt+="A"); }` – mjw Jun 22 '17 at 18:58
  • 1
    Also, see these questions and answers about writing a pad function https://stackoverflow.com/questions/2686855/is-there-a-javascript-function-that-can-pad-a-string-to-get-to-a-determined-leng – Dijkgraaf Jun 22 '17 at 19:00
  • 1
    @mjw you should post that as an answer – Dijkgraaf Jun 22 '17 at 19:03

2 Answers2

4

It is rather easy.

for (var count = 0; count < 7; count++) {
    switch (count) {
        case 7: console.log('AAAAAAA'); break;
        case 6: console.log('AAAAAA'); break;
        case 5: console.log('AAAAA'); break;
        case 4: console.log('AAAA'); break;
        case 3: console.log('AAA'); break;
        case 2: console.log('AA'); break;
        case 1: console.log('A'); break;
        case 0: console.log('xd'); break;
    }
}

Okay... jokes aside.

But for real:

for (var count = 0; count < 7; count++) {
    console.log(new Array(count + 1).join('A'));
}

Or if you badly want to append:

for (var str = ""; str.length < 10; str += "A") {
    console.log(str);
}
Daniel Mizerski
  • 1,123
  • 1
  • 8
  • 24
3

Simple loop for text appending:

var txt = ""; 
for(var count = 0; count < 7; count++) { 
    console.log(txt+="A"); 
}
mjw
  • 1,196
  • 1
  • 12
  • 19