Relational Operators are Tricky

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:

count is 1
count is 2
count is 3
Done with the loop

This is the same as in the first version of the program fragment, but now done differently.

Relational Operators are Tricky

Here is the program fragment:

int count = 1;  
while ( count < 4 )            // there are changes here
{
  System.out.println( "count is:" + count );
  count = count + 1;   
}
System.out.println( "Done with the loop" );      

The relational operator is different than before (now it is <, previously it was <=) and it tests with 4 (previously with 3.) You can figure out what this loop does by observing

  • The count starts out at 1.
  • The last value that will test true in the conditional is 3.
  • count increases by 1 each time.

so the values that are printed out must be: 1, 2, and 3.

The limit value of 4 is coordinated with the relational operator < to control the loop. Here is another change to the program:

int count = 0;  
int limit = 5;
while ( count <  limit )           // there are changes here
{
  System.out.println( "count is:" + count );
  count = count + 1;   
}
System.out.println( "Done with the loop" );      

QUESTION 9:

What does the above program print?