While Loop
The While loop is a repetition structure where the statements in the structure are repeated as long as a Boolean expression is true. The flow of logic keeps coming back up to the Boolean expression to check if it is still true. As soon as the Boolean expression is false, the flow of logic hops down to the end of the loop. Note the Boolean condition is also checked before the looping statements are executed the first time. This mean if the condition is not true the first time, the statements will never happen.
It is a common occurrence to have an accumulator or counter within a looping structure. The counter, usually, is incremented (1 is added) or decremented (1 is subtracted) each time the condition is met and the statements inside the loop are performed. When the counter reaches a certain number that is expressed inside the Boolean statement, then the Boolean expression becomes false and the loop is exited. Ensure you use proper style and DO NOT do what is very common in programming, just declare the variable as i, j or x. Always name a variable for what it is actually doing and holding. For example, if you are using a counter, name it counter or loopCounter. (Yes, I know “i” is short hand for iterator; just do not use it!)
The while loop (in most computer programming languages), takes the generic form of:
WHILE (Boolean expression)
statement(s)
…
counter = counter + 1
ENDWHILE
In this example program, the user is asked to enter a positive integer and the program will count how many times it goes through the loop until it reaches that number.
Top-Down Design for While loop
Flowchart for While loop
Pseudocode for While loop
GET positive_integer
WHILE (counter < positive_integer)
SHOW counter
counter = counter + 1
ENDWHILE
Code for While loop
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 | // Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a while loop
#include <stdio.h>
int main() {
// this function uses a while loop
int counter = 0;
int positiveInteger;
// input
printf("Enter how many times to repeat: ");
scanf("%d", &positiveInteger);
printf("\n");
// process & output
while (counter < positiveInteger) {
printf("%d time(s) through the loop.\n", counter);
counter = counter + 1;
}
printf("\nDone.\n");
return 0;
}
|
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 | // Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a while loop
#include <iostream>
int main() {
// this function uses a while loop
int counter = 0;
int positiveInteger;
// input
std::cout << "Enter how many times to repeat: ";
std::cin >> positiveInteger;
std::cout << std::endl;
// process & output
while (counter < positiveInteger) {
std::cout << counter << " time(s) through the loop." << std::endl;
counter = counter + 1;
}
std::cout << "\nDone." << std::endl;
return 0;
}
|
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 | /* Created by: Mr. Coxall
* Created on: Sep 2020
* This program uses a while loop
*/
using System;
/*
* The Program class
*/
class Program {
static void Main() {
// this function uses a while loop
int counter = 0;
int positiveInteger;
// input
Console.Write("Enter how many times to repeat: ");
positiveInteger = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
// process & output
while (counter < positiveInteger) {
Console.WriteLine(counter + " time(s) through the loop.");
counter = counter + 1;
}
Console.WriteLine("\nDone.");
}
}
|
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
32
33
34
35
36
37 | /*
* This program uses a while loop
*
* @author Mr Coxall
* @version 1.0
* @since 2020-09-01
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// this function uses a while loop
// create Scanner object for user input
Scanner scanner = new Scanner(System.in);
int counter = 0;
// input
System.out.print("Enter how many times to repeat: ");
String positiveIntegerStr = scanner.nextLine();
System.out.println();
// process & output
int positiveInteger = Integer.parseInt(positiveIntegerStr);
while (counter < positiveInteger) {
System.out.println("%d time(s) through the loop.".formatted(counter));
counter = counter + 1;
}
// close the Scanner object
scanner.close();
System.out.println("\nDone.");
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 | /* Created by: Mr. Coxall
* Created on: Sep 2020
* This program uses a while loop
*/
const prompt = require("prompt-sync")()
let counter = 0
// input
const positiveIntegerStr = prompt("Enter how many times to repeat: ")
console.log("")
// process & output
const positiveInteger = parseInt(positiveIntegerStr)
while (counter < positiveInteger) {
console.log(`${counter} time(s) through the loop.`)
counter = counter + 1
}
console.log("\nDone.")
|
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 | #!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module uses a while loop
"""
def main() -> None:
"""The main() function uses a while loop, returns None."""
counter = 0
# input
positive_integer = int(input("Enter how many times to repeat: "))
print("")
# process & output
while counter < positive_integer:
print(f"{counter} time(s) through the loop.")
counter = counter + 1
print("\nDone.")
if __name__ == "__main__":
main()
|
Example Output