knowledge-kitchen / course-notes

Loops - While

Unlike for loops, which are used mostly to repeat a block of code a finite number of times, while loops are most often used to execute a block of code an indefinite number of times. Each repetition is called an iteration.

Iterating through a series of numbers

The following examples all repeat a print statement 6 times in order to print the numbers from 5 to 10, inclusive. The algorithm is as follows:

Python example

i = 5
while i <= 10:
    print(i)
    i += 1;

Java example

int i = 5;
while (i <= 10) {
    System.out.println(i);
    i++;
}

Javascript example

let i = 5
while (i <= 10) {
  console.log(i)
  i++
}

PHP example

$i = 0;
while ($i <= 10) {
    print($i);
    $i++;
}

Iterating through a characters in a string

The following examples all repeat a print statement 9 times in order to print the characters in the string, 'asparagus'. The algorithm is as follows:

Python example

s = "asparagus"
i = 0
while i < len(s):
    c = s[i]
    print(c)
    i += 1

Java example

String s = "asparagus";
int i = 0;
while (i < s.length()) {
    char c = s.charAt(i);
    System.out.println(c);
    i++;
}

Javascript example

let s = "asparagus"
let i = 0
while (i < s.length) {
  let c = s.charAt(i)
  console.log(c)
  i++
}

PHP example

$s = "asparagus";
$i = 0;
while ($i < strlen($s)) {
    $c = $s{$i};
    print($c);
    $i++;
}

Iterating through a values in a list or array

The following examples all repeat a print statement 5 times in order to output each of the following values: 'they', 'sailed', 'away', 'in', 'a', 'sieve', 'they', 'did' - these words are from the first line of The Jumblies, by Edward Lear. The algorithm is as follows:

Python example

list_of_values = [ 'they', 'sailed', 'away', 'in', 'a', 'sieve', 'they', 'did' ]
i = 0
while i < len(list_of_values):
    val = list_of_values[i]
    print(val)
    i += 1

Java example

String[] list_of_values = { "they", "sailed", "away", "in", "a", "sieve", "they", "did" };
int i = 0;
while (i < list_of_values.length) {
    String val = list_of_values[i];
    System.out.println(val);
    i++;
}

Javascript example

let list_of_values = [
  "they",
  "sailed",
  "away",
  "in",
  "a",
  "sieve",
  "they",
  "did",
]
let i = 0
while (i < list_of_values.length) {
  let val = list_of_values[i]
  console.log(val)
  i++
}

PHP example

$list_of_values = array( 'they', 'sailed', 'away', 'in', 'a', 'sieve', 'they', 'did' );
$i = 0;
while ($i < sizeof($list_of_values)) {
    $val = $list_of_values[$i];
    print($val);
    $i++;
}

Validating user input

The following examples use a while loop to ask the user the question, "What's the magic word"? The program repeats asking this question over-and-over until the user enters the valid response, "please". The algorithm is as follows:

Python example

correct_response = "please"
users_response = ""
while users_response != correct_response:
    users_response = input("What's the magic word? ")

Java example

Scanner scn = new Scanner(System.in);
String correct_response = "please";
String users_response = "";
while (!users_response.equals(correct_response)) {
    System.out.println("What's the magic word? ");
    users_response = scn.nextLine();
}

Javascript example

let correct_response = "please"
let users_response = ""
while (users_response != correct_response) {
  users_response = input("What's the magic word?")
}

PHP example

$scn = fopen("php://stdin","r");
$correct_response = "please";
$users_response = "";
while ($users_response != $correct_response) {
    print("What's the magic word?");
    users_response = fgets($scn);
}

Calculating a running total

The following examples ask the user to enter in numbers one at a time. Each new number is added to a running total, which is the sum of all numbers entered so far. The program keeps asking for numbers until the user types 'stop'. The algorithm is as follows:

Python example

total = 0
stop_response = "stop"
users_response = ""
while users_response != stop_response:
    users_response = input("Enter a number: ")
    try:
        val = int(users_response)
        total = total + val
    except:
        print("Sorry, that's not a valid number")
print("The total is " + str(total))

Java example

Scanner scn = new Scanner(System.in);
int total = 0;
String stop_response = "stop";
String users_response = "";
while (!users_response.equals(stop_response)) {
    System.out.println("Enter a number: ");
    users_response = scn.nextLine();
    try {
        int val = Integer.parseInt(users_response);
        total = total + val;
    }
    catch (Exception e) {
        System.out.println("Sorry, that's not a valid number");
    }
}
System.out.println("The total is " + total);

Javascript example

let total = 0
let stop_response = "stop"
let users_response = ""
while (users_response != stop_response) {
  users_response = input("Enter a number: ")
  try {
    let val = parseInt(users_response)
    total = total + val
  } catch (exception) {
    console.log("Sorry, that's not a valid number")
  }
}
System.out.println("The total is " + total)

PHP example

$scn = fopen("php://stdin","r");
$total = 0;
$stop_response = "stop";
$users_response = "";
while ($users_response != $stop_response) {
    print("Enter a number: ");
    $users_response = fgets($scn);
    try {
        $val = (int) $users_response;
        $total = $total + $val;
    }
    catch (Exception $e) {
        print("Sorry, that's not a valid number");
    }
}
print("The total is " + $total);

Accumulator pattern

Any loop where a variable is increasing in value with each iteration.

Infinite loop

A loop that never stops iterating.