Loops and the While Statement

Site: Saylor Academy
Course: CS101: Introduction to Computer Science I
Book: Loops and the While Statement
Printed by: Guest user
Date: Tuesday, 20 May 2025, 8:18 AM

Description

Read this chapter, which explains while loops. This is in contrast to how a do-while loop works, which we will discuss later. In a do-while loop, the body of the loop is executed at least one time, whereas in a while loop, the loop may never execute if the loop condition is false.

1. Loops

Most modern machines work by endlessly repeating the same motions. The engine in your car cycles through the same motions over and over as it burns gasoline to provide power. Electric motors are similar. They convert electric power into circular motion. Because of their circular motions, these machines keep going as long as you want.

Computer programs use cycles, also. In programming, a cycle is called a loop. When a program has a loop in it, some statements are done over and over as long as is needed to get the work done. Most computer programs execute many millions of program statements each time they are used. Usually the same statements are executed many times. This chapter discusses several kinds of programming loops.

Chapter Topics:

      • The while statement
      • Syntax and semantics of the while statement
      • The loop body
      • Three parts of a loop that must be coordinated
      • Counting loops and the loop control variable

Question 1:

Think of some machines (mechanical or other) that use cycles.


Source: Bradley Kjell, http://programmedlessons.org/Java9/chap19/ch19_01.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License.

2. The while statement


Answer:

Some Machines that Use Cycles

      • Bicycle — your legs drive the pedals connected to a gear which spins.
      • DVD Player — the disk spins (cycles) as the laser moves across it.
      • TV Set — pictures are put one the screen one after another as long as the set is on.
      • Water Pump — often a piston repeatedly moves in and out of a cylinder.
      • Laundry Dryer — rotating drum.
      • Clock — shows the same times every day. If the clock is mechanical, its insides are gears and
        springs with many mechanical cycles.
        If the clock is electronic the cycles are still there, but harder to see.
      • Sun and the Earth — endlessly cycling, seasons flowing one into the next.

Perhaps the ultimate example of the usefulness of cycles is the ultimate machine — the wheel.

The while statement

Here is a program with a loop. It contains a while statement, followed by a block of code. A block is a group of statements enclosed in brackets { and }.


// Example of a while loop public class LoopExample { public static void main (String[] args ) { // start count out at one int count = 1; // loop while count is <= 3 while ( count <= 3 ) { System.out.println( "count is:" + count ); // add one to count count = count + 1; } System.out.println( "Done with the loop" ); } }

while

The flowchart shows how the program works. First, count is set to one. Then it is tested by the while statement to see if it is less than or equal to three.

The test returns true so the statements in the block following the while are executed. The current value of count is printed, and count is incremented. Then execution goes back to the while statement and the test is performed again.

count is now two, the test returns true and the block is executed again. The last statement of the block increments count to three, then execution goes back to the while statement.

count is now three, the test returns true and the block is executed again. The last statement of the block increments count to four, then execution goes back to the while statement.

After the block has executed three times, count is four. Execution goes back to the while statement, but now the test returns false, and execution goes to the "Done with loop" statement. Then the program ends.

Copy this program to a file and run it. Then play with it. See if you can change the program so it prints one through ten. Then change it so that it prints zero through ten.


Question 2:

What does this statement do:

    count = count + 1;

3. Incrementing count


Answer:

    count = count + 1;
It increases count by one.

Incrementing count


If the answer is not clear, remember the two steps of an assignment statement:

  • first evaluate the expression on the right of the equal sign,
  • second put the value in whatever variables on the left.

Say that count is 2. When the above statement executes, first the expression count + 1 is evaluated, resulting in 3. Second the 3 is put in count.


Question 3:

What does this statement do:

    count = count + 2;

4. More on the while Loop


Answer:

    count = count + 2;
This adds two to the variable count.

More on the while Loop


Here is the part of the program responsible for the loop:

// start count out at one
int count = 1;       

// loop while count is <= 3                           
while ( count <= 3 )                                
{
  System.out.println( "count is:" + count );    
  
  // add one to count
  count = count + 1;                               
}
System.out.println( "Done with the loop" ); 

Here is how it works in detail. Look especially at steps 7, 8, and 9.


Skip this page if you are clear how the while loop works. But study it if you still have some doubts.

  1. The variable count is assigned a 1.
  2. The condition ( count <= 3 ) is evaluated as true.
  3. Because the condition is true, the block statement following the while is executed.
      • The current value of count is written out:    count is 1
      • count is incremented by one, to 2.

  4. The condition ( count <= 3 ) is evaluated as true.
  5. Because the condition is true, the block statement following the while is executed.
      • The current value of count is written out.   count is 2
      • count is incremented by one, to 3.

  6. The condition ( count <= 3 ) is evaluated as true.
  7. Because the condition is true, the block statement following the while is executed.
      • The current value of count is written out.   count is 3
      • count is incremented by one, to 4.

  8. The condition ( count <= 3 ) is evaluated as FALSE.
  9. Because the condition is FALSE, the block statement following the while is SKIPPED.
  10. The statement after the entire while-structure is executed.
      • System.out.println( "Done with the loop" );

Question 4:

  1. How many times was the condition true?
  2. How many times did the block statement following the while execute?

5. Syntax of the while statement


Answer:

  1. How many times was the condition true? 3
  2. How many times did the block statement following the while execute? 3

Syntax of the while statement


Here is the syntax for the while statement:

while ( condition )
statement

Varieties of while Statements
while ( condition )
statement;
while ( condition )
{
one or more statements
}

Notes:

      • The condition is a Boolean expression: something that evaluates to true or false.
      • The condition can be complicated, using many relational operators and logical operators.
      • The statement is a single statement. However it can be (and usually is) a block statement containing several other statements.
      • The statement is sometimes called the loop body.

Since the statement can be a single statement or a block statement, a while statement looks like either choice in the table. Almost always, though, a while statement is used with a block.

The style of indenting used here leads to fewer errors than alternative styles. The statements controlled by the while are indented. The braces of the block are aligned with each other and with the while and each is put on its own line.


Question 5:

Is the condition always surrounded by parentheses?

6. Semantics of the while statement


Answer:

Yes.

Semantics of the while statement


Here is the while statement, again:

while ( condition )
loop body // a statement or block statement

statement after the loop

Here is how the while statement works. In the following, the word control means "the statement that is executing".

  • When control reaches the while statement, the condition determines if the loop body is to be executed.
  • When the condition is true, the loop body is executed.
    • After the loop body is executed, control is sent back to the while, which again evaluates the condition.
  • When the condition is false, the loop body is skipped.
    • Control is sent to whatever statement follows the loop body.
  • Once execution has passed to the statement after the loop, the while statement is finished, at least for now.
  • If the condition is false the very first time it is evaluated, the loop body will not be executed even once.

Here is the while loop from the example program:

int count = 1;                                  // start count out at one
while ( count <= 3)                             // loop while count is <= 3
{
  System.out.println( "count is:" + count );
  count = count + 1;                            // add one to count
}
System.out.println( "Done with the loop" );     // statement after the loop           

This loop uses the variable count. It is started out at 1, then incremented each time the loop body is executed until it reaches 4 and the condition is false. Then the statement after the loop is executed.


Question 6:

The variable count is used in three different activities. It is initializedtested,
and 
changed. Where in the program does each of these events take place?

7. Three Activities to Coordinate


Answer:

int count = 1;              // count is initialized
while ( count <= 3 )        // count is tested
{
  System.out.println( "count is:" + count );
  count = count + 1;        // count is changed
}
System.out.println( "Done with the loop" );      

Three Activities to Coordinate


Three activities of a loop must work together:

  1. The initial values must be set up correctly.
  2. The condition in the while statement must be correct.
  3. The change in variable(s) must be done correctly.

In the above program we wanted to print the integers "1, 2, 3". Three parts of the program had to be coordinated for this to work correctly.


Question 7:

What will the program print if the initialization is changed as follows?

    int count = 0; // count is initialized while ( count <= 3 ) // count is tested { System.out.println( "count is:" + count ); count = count + 1; // count is changed } System.out.println( "Done with the loop" );

8. Boundary Conditions


Answer:

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

Boundary Conditions


To determine what a loop does, look at the following:

      • Look at the initialization.
      • Look at the condition to determine when the loop ends.
      • Look at what change is made each time the loop body executes.

Sometimes these are called boundary conditions because they occur at the boundaries of the loop body and greatly affect what the loop does. The name "boundary condition" is an analogy to mathematics, where how a mathematical function behaves depends on its values at the boundaries of an interval.

Here is another version of the example fragment:

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

The loop condition has been changed from the previous version.

Question 8:

What does the program print out?

9. Relational Operators are Tricky


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 from 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

      • count starts out at 1.
      • The last value that will test true in the condition 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?

10. Complete Program


Answer:

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

Complete Program

Here is a complete program that lets the user pick the initial value and the limit value:

import java.util.Scanner;

// User picks starting and ending value
public class loopExample
{
  public static void main (String[] args )  
  {
    Scanner scan = new Scanner( System.in );
    int count, limit;

    System.out.print( "Enter initial value: " );
    count = scan.nextInt();

    System.out.print( "Enter limit   value: " );
    limit = scan.nextInt();

    while ( count <= limit )   // less-than-or-equal operator
    {
      System.out.println( "count is: " + count );
      count = count + 1;
    }
    System.out.println( "Done with the loop" );
  }
}

Of course, you will want to copy this program to a file and compile and run it.

Question 10:

If the user sets the initial value to -2 and the limit value to 1 what values will be printed out?

11. Web Page Version of the Program


Answer:

    count is: -2
    count is: -1
    count is: 0
    count is: 1
    
Zero is included in the list of values!

Web Page Version of the Program

You might enjoy playing with this JavaScript version of the program. Try a variety of initial and limit values. Predict what the loop does for each choice.

If the output does not fit into the text area, use the "scroll bar" on the right to move up and down through the output.

int count =  ;
int limit =  ;
while ( count <= limit ) 
{
  System.out.println( "count is:" + count );
  count = count + 1;
}
System.out.println( "Done with the loop" );
   


(The output window sometimes shows messages that would not be printed by the example code.)


Question 11:

Try entering an initial value of 9 and a limit value of 4. What happens? Why?

12. Loop Control Variable


Answer:

The loop does not execute, even once. This is because the condition of the while statement,

    count <= limit

is false the first time. The statement following the loop,

    System.out.println( "Done with the loop" );

does execute.

Loop Control Variable

All the while loops in this chapter look something like this:

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

The variable count is initialized, tested, and changed as the loop executes. It is an ordinary int variable, but it is used in a special role. The role is that of a loop control variable. Not all loops have loop control variables, however.

The type of loop we have been looking at is a counting loop, since it counts upwards using the loop control variable as a counter. You can make counting loops with statements other than the while statement, and not all while loops are counting loops.


Question 12:

Do you think that a counting loop will always count upwards by ones?

13. End of the Chapter


Answer:

No. Counting loops can count up by two's, for example. This is a topic for a future chapter.

End of the Chapter

We have reached the limit of this chapter. You may wish to review the following. Click on a subject that interests you to loop back to where it was discussed.