# Thread: Assignment involving for and while loops

1. Member
Join Date
Feb 2013
Posts
9
Rep Power
0

## Assignment involving for and while loops

So my prof just handed out this assignment. It's basically calculating the time it would take for an object at a certain height to hit the ground. Then comparing that to the analytical answer (formula)

Here's what I have so far

Java Code:
```package egr118;
public class Lab3 {

public static void main(String[] args) {

double g = 9.807; //acceleration due to gravity
double p_0 = 5; // initial height in meters
double p = p_0; // p starts at p_0
double v_0 = 0; // no velocity
double dt = 1./10; // time step in seconds
double t = 0; // start at time 0
double at = 0;

while (p>0)
{
p = v_0 * t - 0.5 * g * t * t + p_0; //basically physics equation to determine position
t += dt;
}

System.out.println("Final Time = " + t);

at = timeOfFlight(g , p_0); // analytical time using method below
System.out.println("Analytical answer = " + at);

double error = (((t - at) / at)* 100);
System.out.println("\nThere is a " + error + "% error" );

}

public static double timeOfFlight(double g, double p_0) // we have to create a new method to do the analytical answer for us
{
return (double) Math.sqrt(2*p_0 / g);
}
}```

So the output would give us the time based on the formula above and the analytic formula in the new method. And then compare them and print out the error percentage.

Now I'm on to the 3rd step which says:

3) "Place the code so far inside of a "for" loop so that you can repeat your calculations faster. Change the double dt = 1./10 to double dt = 1./Math.pow( 2 , i );

for ( int i = 1; i < 6; i++ )
{
double dt = 1./Math.pow ( 2 , i );
...
}

What do you think he means by place it in a for loop? I already have a while loop in the code...do i keep it and leave it inside the for loop?

Thanks for any help

2. Member
Join Date
Feb 2013
Posts
9
Rep Power
0

## Re: Assignment involving for and while loops

I just placed the while loop inside the for loop. It never states to replace it so I just left it.

Now I have an extra credit portion

I have to modify the code to output all of the values as they are computed, load them into a spreadsheet, and plot the height vs time.

I have NO idea how to do that...i mean...to get the outputs as they are received I can just place the

Java Code:
` System.out.println(t);`
inside the loop.

But how do I load them into a spreadsheet or anything like that?

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•