10 - For Loops

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

Code HuntJava
1.0x

10 - For Loops

Created 3 years ago

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

    Slide 2 - for Loops

  2. for Loops

    Slide 3 - for Loops

    • A loop is a syntactic construct that causes code to potentially be executed more than once.
    • The simplest loop in Java is the for loop:
    • for (<initialization>; <test>; <update>) {
    • <statement>;
    • <statement>;
    • <statement>;
    • }
  3. for Loop Components

    Slide 4 - for Loop Components

    • The parts of a for loop are:
    • Initialization: Usually a variable declaration, but can be any statement
    • Test: Any Boolean expression
    • Update: Usually alters the variable declared in the initialization, often with compound assignment
    • Body: The sequence of statements to be executed repeatedly
  4. for Loop Control Flow

    Slide 5 - for Loop Control Flow

    • The order of execution, or control flow, of a for loop is as follows:
    • Execute initialization
    • Evaluate the test
    • If the test is false, exit the loop (terminate)
    • Execute body
    • Execute update
    • Return to step 2 (iterate)
    • Note that:
    • The initialization is only executed once
    • The body may not be executed at all
  5. for Loop Example

    Slide 6 - for Loop Example

    • for (int i = 1; i <= 4; i++) {
    • System.out.println("Hello!");
    • }
  6. More for Loop Examples

    Slide 7 - More for Loop Examples

    • for (int j = 5; j >= 1; j--) {
    • System.out.println(j + "...");
    • }
    • System.out.println("Blast off!");
    • String s = "Java";
    • String result = "";
    • for (int c = 0; c < s.length(); c++) {
    • result += s.charAt(c);
    • result += s.charAt(c);
    • }
    • System.out.println(result);
    • int n = 0;
    • String line = "";
    • for (int num = 0; num < n; num++) {
    • line += num + " ";
    • }
    • System.out.println(line);