11 - While Loops

Get an introduction to or review of while loops in Java programming.

Code HuntJava
1.0x

11 - While Loops

Created 3 years ago

Duration 0:06:13
lesson view count 2
Get an introduction to or review of while loops in Java programming.
Select the file type you wish to download
Slide Content
Tags: Code Hunt Java
  1. while Loops

    Slide 2 - while Loops

  2. while Loops

    Slide 3 - while Loops

    • The while loop is the most flexible loop in Java:
    • while (<test>) {
    • <statement>;
    • <statement>;
    • <statement>;
    • }
    • The parts of a while loop are:
    • Test: Any Boolean expression
    • Body: The sequence of statements to be executed repeatedly
  3. while Loop Control Flow

    Slide 4 - while Loop Control Flow

    • The control flow of a while loop is as follows:
    • Evaluate the test
    • If the test is false, exit the loop (terminate)
    • Execute body
    • Return to step 1 (iterate)
    • Unlike in a for loop, there is no explicit initialization or update.
    • Be careful of infinite loops!
  4. while Loop Example

    Slide 5 - while Loop Example

    • int n = 1;
    • while (n <= 4) {
    • System.out.println("Hello!");
    • n++;
    • }
  5. More while Loop Examples

    Slide 6 - More while Loop Examples

    • int sum = 0;
    • int i = 1;
    • while (sum < 50) {
    • sum += i;
    • i++;
    • }
    • System.out.println(sum);
    • String s = "aaaa";
    • int c = 0;
    • while (s.charAt(c) != 'a') {
    • c++;
    • }
    • System.out.println(c);
    • int x = 5;
    • while (x > 0) {
    • System.out.println(x);
    • }