Nesting Loops and Ifs
15. Gravity Program Skeleton
Answer:
- What kind of loop will be used? A counting loop, since
t
will increase until it hits a limit. - What is the loop control variable? Time,
t
, since it is increased, second by second. - What does the loop body do? It calculates distance for the current value of
t
, then increases t
.
Gravity Program Skeleton
The program looks like this:
import java.util.Scanner; // User picks ending value for time, t. // The program calculates and prints // the distance the brick has fallen for each t. // public class FallingBrick { public static void main (String[] args ) { final double G = 9.80665; // constant of gravitational acceleration int t, limit; // time in seconds; ending value of time double distance; // the distance the brick has fallen Scanner scan = new Scanner( System.in ); // Get the number of seconds System.out.print( "Enter limit value: " ); limit = scan.nextInt(); // Print a table heading System.out.println( "seconds\tDistance" ); // '\t' is tab System.out.println( "-------\t--------" ); t = ; // calculate the distance for each second while ( ) { (more statements will go here later.) t = } } } |
Question 15:
First get the loop correct. Three things must be coordinated: Time starts at zero, increases by one second each iteration, and when time
equals limit
the last value is printed out.