Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Loop predicament in Java

  1. Oct 19, 2011 #1
    ..so, we have been assigned a homework to print a certain ASCII art using only loops and methods. We can also use the built-in math methods such as the exponential one and whatnot.

    Basically, we have been asked to print an increasing loop that goes as follows:
    Code (Text):
    ..and so on, so forth. Notice how the stars increase by 2 then by 4, then by 2 then by 4. The sequence in which the stars are increasing within is 2,4,2,4,2,4,2,4...I managed to find the series for that: 3 + (-1)^n or 2 + 2 * (n % 2) where n >= 1.

    Is there a way to use that in a loop? I'm slightly bewildered at the moment as this problem overwhelms my basic understanding on loops.
  2. jcsd
  3. Oct 19, 2011 #2


    Staff: Mentor

    Are you sure about how the numbers of asterisks in a line increase? It would make more sense to me and would make a nicer pattern if they increased by 2 each line.
  4. Oct 19, 2011 #3
    Unfortunately, this is how our instructor assigned us to do. I tried like everything, but no avail. This is just a fraction of a larger program that prints my country's flag.

    Is there a way to do that?
  5. Oct 19, 2011 #4


    Staff: Mentor

    The counting loop would look something like this.

    Code (Text):

    for (int i = 0; i < ROW_LIMIT; i++}
       starCount = 2*i + 1;
       // The if block skips 5, 11, 17, 23, etc.
       if (starCount % 3 == 2)
       // Code to calculate the number of spaces to print, and print starCount asterisks
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook