Suzanne O. answered • 10/07/21

International Experience and Multiple State Certifications

Hi Fin.

Your question:

How can I define a* for loop *for the following output:

1+2 = 3

2+3 = 5

4+5 = 9

8+9 = 17

16+17 = 33

32+33 = 65

64+65 = 129

...is an interesting one.

I can see two sticking points:

- the math that will give the desired output
- the java
loop code*for*

For the math, the first pattern I see is 1+2, 2+3, 4+5... which translates to:

**x+x+1** or **x*2+1**

The second pattern I see is 1, 2, 4, 8, 16, 32, 64. That one translates to:

**x*2** (with **x** starting at 1)

The first equation (**x+x+1 **or **x*2+1, **either one will work) is part of the content (code block) of your ** for **loop, the second equation (

**x*2**) is the increment to control the loop.

It's hard to write code in this answer box (it wants to handle the actual code), but I'll give it a try:

So to begin defining your loop:

statement 1 should read something like** int x=1** (you are to start with x equals 1)

statement 2 should read something like **x<=64** (64 is where you stop)

statement 3 should read something like **x=x+x** or **x=x*2** (your increment)

And your output statement needs to be a bit creative to get the proper formatting, something like:

This is the straight forward, non-elegant approach, and you will have to complete the code. ** Elegance **comes from combining steps into fewer lines of code.

Here are some links that can help:

https://www.geeksforgeeks.org/difference-between-print-and-println-in-java/

https://www.w3schools.com/java/java_for_loop.asp

https://www.geeksforgeeks.org/java-for-loop-with-examples/

and for a bit more elegance in your print()/println():

https://www.geeksforgeeks.org/java-for-loop-with-examples/

Happy coding!

Fin M.

thank you so much10/07/21