Jump to content

How to fix loop in Java?

- - - - -

  • Please log in to reply
3 replies to this topic

#1
Hiche

Hiche

    Newbie

  • Members
  • Pip
  • 9 posts
...so, I'm taking an introduction course on the Java language and so far it has been good. However, I am struggling with a loop that isn't within my scope of comprehension.

Basically, I want a loop to print this:

       *

      ***

    *******

..and so on, so forth. Notice how the stars are increasing by, firstly, 2, then by 4. It was one star, then 3 (by 2), then 7 ( by 4)..and so on. The spacing is irrelevant to my code; I know how to manipulate the increase or decrease of white spaces. I will use dots instead of spacing, though.

The only thing I thought of is the sequence in which the 2,4,2,4.. series follows: 3 + Math.pow(-1, i) where i is an initialization variable in the main for loop.

Any thoughts on this? Thanks.

#2
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
stars(i) = (2^i) - 1 where i > 0
stars(1) = (2^1) - 1 = 1
stars(2) = (2^2) - 1 = 3
stars(3) = (2^3) - 1 = 7
stars(4) = (2^4) - 1 = 15
...
stars(10) = (2^10) - 1 = 1,023

#3
Hiche

Hiche

    Newbie

  • Members
  • Pip
  • 9 posts
Not quite.

You see, I want the numbers of stars to increment by 2 then by 4, then by 2 the by 4..

1 star
(+2)
3 stars
(+4)
7 stars
(+2)
9 stars
(+4)...
13 stars
15 stars
19 stars
..

...and so on.

#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
You can do
2 + 2*(i%2)





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users