Rows of Stars

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

Recall that for maximum accuracy, the loop control variable should be an integer type. So the modified loop should look like this:

tenths = 0 ;
while (  tenths <= limit*10 )    
{
  double t = tenths/10.0 ;        // be sure to include "point zero"
  distance = (G * t * t)/2 ;
  System.out.println( t + "/t" + distance );

  tenths = tenths + 1 ;
}

It is best to leave the formula as it was in the previous program, and to handle the calculation of t from tenths in an extra statement. (Sometimes people try to skip the extra statement by modifying the formula, but this saves little or no computer time, and costs possible confusion and error.)

Rows of Stars

We want a program that writes out five rows of stars, such as the following:

*******
*******
*******
*******
*******

This could be done with a while loop that iterates five times. Each iteration could execute

 
System.out.println("*******")

But it is more useful to ask the user how many lines to print, and how many stars are in each line:

Lines? 3
Stars per line? 13

*************
*************
*************

Now the user might ask for any number of stars per line, and no single println can do that.

QUESTION 18:

Can a counting loop, such as we have been using, be used to count up to the number of lines that the user requested?