coderPro97 - 7 months ago 38

Java Question

I'm working on a Java program that prints a sine wave to the console. This is what I've written so far:

`int num = 7;`

for (double y = 2; y >= 0; y-=0.2) {

for (double x = 0; x <= num; x+=0.2) {

if ( ((0.1+x) >= Math.asin((double)y-1)) && (((double)x-0.1) <= Math.asin((double)y-1)) )

System.out.print('*');

else

System.out.print(' ');

}

System.out.println();

}

Essentially, this program treats each character on each line as a 0.2 x 0.2 area on a coordinate plane. If the sine function crosses this area, an asterisk is printed to the screen. Otherwise, a space is printed.

When run, this is printed to the console:

`*`

*

*

*

*

*

Can anybody tell me why my program stops after printing the first quarter of the wave?

Answer

The reason it only prints the first quarter of the sine wave is because of the indicated range of `Math.asin`

:

Returns the arc sine of a value; the returned angle is in the range -pi/2 through pi/2.

Once you advance `x`

past `Math.PI / 2`

, then the `if`

statement's condition will always be `false`

.

You can take advantage of the fact that

sin(π - *x*) = sin(*x*)

and

sin(2π - *x*) = -sin(*x*)

by including more conditions. (I've also removed the unnecessary casts to `double`

for clarity.)

```
if ( (0.1+x >= Math.asin(y-1)) && (x-0.1 <= Math.asin(y-1)) ||
(0.1+x >= Math.PI - Math.asin(y-1)) && (x-0.1 <= Math.PI - Math.asin(y-1))
(2*Math.PI -(0.1 + x) <= -Math.asin(y-1)) && (2*Math.PI -(x-0.1) >= -Math.asin(y-1)) )
```

Output:

```
*
* *
* *
* * *
* * *
* * *
* *
* *
* *
* *
*
```