Incrementing by a Variable

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   hear noise   go to next page

Answer:

Now show the for statement for each of the following sequences

start at 0, count upward by 1's, end at 7 for ( count = 0; count < 8; count++ )
start at 0, count upward by 2's, end at 14 for ( count = 0; count < 15; count += 2 ) start at 1, count upward by 2's, end at 15 for ( count = 1; count < 16; count += 2 )

Incrementing by a Variable

Here is a program fragment and its JavaScript equivalent that uses an increment amount contained in a variable.

int inc;

// ... get inc from the user ...

for ( count = 0; count < 21; count = count + inc )  
{
  System.out.println( "count is: " + count ); 
}
System.out.println( "/nDone with the loop./nCount is now" + count);

Here is a JavaScript version of this loop. Try to predict what will be output each time you run the program.



Enter increment value:

QUESTION 9:

What is the smallest value of inc such that the loop body will execute only one time? Confirm your answer by testing it with the program.