ash182
ash182

Reputation: 23

How to print different characters using just one for loop

I have to print the following American Flag to the screen:

*****=====
*****=====
*****=====
==========
==========
==========

(*****===== 5 *’s and 5 =’s) (6 lines in total)

I am only allowed to use one for loop and I cannot use the same System.out.print(); twice.

Currently I have:

for (x = 1; x <= 3; x++) {
    System.out.println("*****=====");
}
for (x = 1; x <= 3; x++) {
    System.out.println("==========");
}

This works, but it has two for loops and I can't figure out how to do it with just one.

Upvotes: 1

Views: 1264

Answers (4)

CA Martin
CA Martin

Reputation: 367

for (int x = 1; x <= 6; x++)        
    System.out.println(x<4 ? "*****=====" : "=========");

or

for (int x = 1; x <= 6; x++)System.out.println(x<4 ? "*****=====" : "=========");

Shortest possible I could come up with....

Upvotes: 0

Holger
Holger

Reputation: 298539

This is an invitation to be creative.

without loop

    System.out.println(
        "*****=====\n"
       +"*****=====\n"
       +"*****=====\n"
       +"==========\n"
       +"==========\n"
       +"==========");

or

    System.out.print("*****");
    System.out.println("=====");
    System.out.print("*****=");
    System.out.println("====");
    System.out.println("*****=====");
    System.out.println("==========");
    System.out.print("=======");
    System.out.println("===");
    System.out.print("=");
    System.out.println("=========");

See, no repeating print statement…

With one loop

    for(int i=0; i<6; i++)
        if(i<3)
            System.out.println("*****=====");
        else
            System.out.println("==========");

or, as more experience developers might write it

    for(int i=0; i<6; i++)
        System.out.println(i<3? "*****=====": "==========");

or, to get bonus points for creativity

String string="*****==========";

for(int i=0, s=0; i<6; i++, s=i/3*5)
    System.out.println(string.substring(s, s+10));

You see, there are more than one way to achieve a goal… The important thing is that you try to understand how these examples work to add the features of the Java language to your own tool set. Maybe you will create your own alternative solution then.

Upvotes: 5

uthavaakkarai
uthavaakkarai

Reputation: 178

String firstPart = "*****";
String secondPart = "=====";
for (int i=0; i < 6; i++) {
    System.out.println(firstPart + secondPart);
    if (i == 2) {
        firstPart = "=====";  
    }
}

Upvotes: 1

wadda_wadda
wadda_wadda

Reputation: 1004

Use an if condition inside of your for loop:

for (int i=0; i < 6; i++) {
  if (i < 3) {
    System.out.println("*****=====");
  } else {
    System.out.println("==========");
  }
}

Upvotes: 1

Related Questions