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.

4
  • 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 Commented Jun 22, 2017 at 18:56
  • 2
    var txt = ""; for(var count = 0; count < 7; count++) { console.log(txt+="A"); } Commented Jun 22, 2017 at 18:58
  • 1
    Also, see these questions and answers about writing a pad function stackoverflow.com/questions/2686855/… Commented Jun 22, 2017 at 19:00
  • 1
    @mjw you should post that as an answer Commented Jun 22, 2017 at 19:03

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

10 Comments

That would work, but rather unwieldy and doesn't scale well. e.g. if you had to do that 1000s of times
I gave better answer :)
Danny, you code only works for count = 1 through 7. What if I want 8 or more? ;-P
@vbguyny copypaste more!!
people have no shame
|
3

Simple loop for text appending:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.