Skip to content

A while Loop With Unknown Loop Count

Unknown Loops with while

When we code a loop that does not have a preset number of loops we need a way to stop the loop when it is done. There are two common approaches:

  1. Loop until some predetermined value is read, like "quit".
  2. Loop and read data until the end of the data.

Stop On A Sentinel

sen•ti•nel noun 1. a soldier or guard whose job is to stand and keep watch. 2. figurative something that appears to be standing guard or keeping watch.

In programming, the term sentinel means a special value that a program is looking for to take certain actions. Here are some examples.

  • A program that asks a user for words until the entered word is, "quit".
  • A program that reads records from a file until it reaches a customer number that is 999999.
  • A program that performs security scans on a hard drive every half hour until midnight, it then outputs a report for the previous day and starts over.

** Click me to run askForNumbers() function call **

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
  This function is in file unit04/demos/js/whileUnknownCount.js
  It loops until the user enters "quit"
*/

function askForNumbers() {
    "use strict";

    // Declare Constants
    const INITIAL_VALUE = 0;
    const QUIT_CODE = "quit";

    // Declare Variables
    let number;
    let total;

    // Assign initial values for variables
    total = INITIAL_VALUE;

    while (number !== QUIT_CODE) {
        number = prompt("Enter a number or \"quit\"");

        if (number !== QUIT_CODE) {
            number = Number(number);
            total += number;
            document.write("You entered: " + number + "<br />");
        }
    }

    document.write("Your total is: " + total + "<br />Goodbye!");
}

A Sentinel in the data

Sometimes a sentinel is just part of the data as in this example.

** Click me to run lookForFive() function call **

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
    This function is in file unit04/unit04/js/whileUnknownCount.js.
    It loops until the user enters 5.
*/
function lookForFive() {
    "use strict";

    // Declare Constants
    const INITIAL_VALUE = 1;
    const QUIT_CODE = "5";

    // Declare Variables
    let number;
    let counter;

    // Assign initial values for variables
    counter = INITIAL_VALUE;

    while (number !== QUIT_CODE) {
        number = prompt("Enter the number " + counter);
        document.write("You entered " + number + "<br />");

        counter++;
    }

    document.write("Bye, bye!");
}

Comparison to Stop a Loop

Frequently, we need to compare two values to determine if we stop a loop

** Click me to run comparison() function call **

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
    Stopping a loop with a comparison
*/

function comparison() {
    "use strict";

    // Declare Constants
    const INITIAL_VALUE = 0;
    const TARGET_NUMBER = 100;

    // Declare Variables
    let enteredNumber;

    // Assign initial values for variables
    enteredNumber = INITIAL_VALUE;

    while (TARGET_NUMBER > enteredNumber) {
        enteredNumber = prompt("Enter a Number Less than" + TARGET_NUMBER);
        enteredNumber = Number(enteredNumber);
        document.write("Entered Number: " + enteredNumber + "<br />");
    }
}

It works with characters, too.

** Click me to run comparisonCharacters() function call **

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
    Stopping a loop by comparing characters
*/

function comparisonCharacters() {
    "use strict";

    // Declare Constants
    const QUIT_CODE = "Z";

    // Declare Variables
    let enteredCharacter;

    enteredCharacter = prompt("Enter a letter that is less than 'Z'");

    while (enteredCharacter < QUIT_CODE) {
        document.write(enteredCharacter + " is less than " + QUIT_CODE + "<br />");
        enteredCharacter = prompt("Enter a letter that is less than 'Z'");
    }

    document.write(enteredCharacter + " is bigger than " + QUIT_CODE);
}

Read until we're done

  • Our programs read data from sources like files and database tables.
  • We usually need to read until we've read everything.
  • Sentinels are not used as much as they used to be. Modern languages are better equipped to loop until we're done.
  • Here's a detailed example using the Student Exam Records set. Here is the entire data set:
Student Exam Score
"Bill Smith" 78
"Sue Johnson" 89
"Jill Green" 99
"Steve Brown" 83
"Nancy Brown" 95
"Tom Little" 90

In our Record Set system for the course we know that in order to read these records we first need to do this:

1
2
// Accessing the records let records;
records = openStudentExamRecords();

This function gives us access to the records set but not to the first record. You could think of it as pointing to the spot before the first record. Like this:

Student Exam Score
Current Record
"Bill Smith" 78
"Sue Johnson" 89
"Jill Green" 99
"Steve Brown" 83
"Nancy Brown" 95
"Tom Little" 90

Next we call records.readNextRecord(); at the top of a while loop, which will cause the first record to be available.

Student Exam Score
"Bill Smith" 78 Current Record
"Sue Johnson" 89
"Jill Green" 99
"Steve Brown" 83
"Nancy Brown" 95
"Tom Little" 90

Then within the loop we use functions that start with "get" to read each field of the record. For this record set we use:

  • records.getStudentName();
  • records.getStudentScore();

Because the current record is the first one, these functions return:

  • Student Name: Bill Smith
  • Student Score: 78

The next step is to move to the next record. The while loop starts again with calling records.readNextRecord();

If there is another record this function moves our current record to the next one.

Student Exam Score
"Bill Smith" 78
"Sue Johnson" 89 Current Record
"Jill Green" 99
"Steve Brown" 83
"Nancy Brown" 95
"Tom Little" 90

Then "get" functions will now retrieve:

  • Student Name: Sue Johnson
  • Student Score: 89

Then the loop starts over with records.readNextRecord(); and moves our current record forward.

Student Exam Score
"Bill Smith" 78
"Sue Johnson" 89
"Jill Green" 99 Current Record
"Steve Brown" 83
"Nancy Brown" 95
"Tom Little" 90

We continue to move the current record and read the data from the current record until we get here:

Student Exam Score
"Bill Smith" 78
"Sue Johnson" 89
"Jill Green" 99
"Steve Brown" 83
"Nancy Brown" 95
"Tom Little" 90 Current Record

Now with the next call to records.readNextRecord(); something different happens. When there are no more records to read this function will return false and the loop will stop.

Student Exam Score
"Bill Smith" 78
"Sue Johnson" 89
"Jill Green" 99
"Steve Brown" 83
"Nancy Brown" 95
"Tom Little" 90
return false; Current Record

Quick Example

Here's what this looks like in a very small program. All the looping elements are here.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function quickExamScoresExample() {
    "use strict";

    let results;

    results = openStudentExamRecords();

    while (results.readNextRecord()) {
        document.write(results.getStudentName() + ", "
                + results.getStudentScore() + "<br />");
    }
}



Demo

Demo

  1. Demo: Print Examination Scores
    • unit01/demos/demo-exam-scores.html

Everything should be made as simple as possible, but not simpler. - Albert Einstein

Labs

Labs

  1. Lab07: Unknown Loop Count
    • unit04/labs/lab-07-unknown-count.html

Exercises

Exercises

  1. Exercise07: Exercise for Lab 07
    • unit04/exercises/exercise-07.html