slanted W3C logo

Day 15 — for Loops

In today's lecture we discuss looping.

for Loop Example 1

The for statement lets you repeat a block of code. The number of times the block is repeated is controlled by a logical statement.

For example, suppose you wanted to write a program that reads in 10 numbers from a user and computes the sum.

import java.io.PrintStream;
import java.util.Scanner;

public class ForExample1
{
   public static void main(String[] args)
   {
      PrintStream output = System.out;
      Scanner input = new Scanner(System.in);

      final int N = 10;
      int sum = 0;
      for (int i = 0; i < N; i = i + 1)
      {
         output.print("Enter a number : ");
         sum = sum + input.nextInt();
      }
      output.println("The sum is : " + sum);
   }
}

for Loop Example 2

Suppose you wanted to write a program that prints a user supplied number of *s.

import java.io.PrintStream;
import java.util.Scanner;

public class ForExample2
{
   public static void main(String[] args)
   {
      PrintStream output = System.out;
      Scanner input = new Scanner(System.in);

      output.print("How many *s do you want to print? ");
      final int N = input.nextInt();
      for (int i = 0; i < N; i++)
      {
         output.print("*");
      }
   }
}

for Loop Example 3

Suppose you wanted to write a program that sums the first N integers 1, 2, 3, ..., N

import java.io.PrintStream;
import java.util.Scanner;

public class ForExample3
{
   public static void main(String[] args)
   {
      PrintStream output = System.out;
      Scanner input = new Scanner(System.in);

      output.print("Enter a value for N: ");
      final int N = input.nextInt();
      int sum = 0;
      for (int i = 1; i <= N; i++)
      {
         sum = sum + i;
      }
      output.printf("The sum of the first N integers is: %d%n", sum);
   }
}

Structure of the for Loop

The for loop is controlled by 3 expressions, all of which are optional.

      for (initial-expression; logical-expression; update-expression)
      {
         statements
      }

The loop executes as follows:

  1. The initial-expression executes.
  2. The logical-expression is evaluated. If it is true then:
    1. The body statements are executed.
    2. The update-expression is executed.
  3. Step 2 is repeated.

Tracing a Loop

Suppose we have the following loop that computes the sum 0 + 1 + 2:

      int sum = 0;
      for (int i = 0; i < 3; i++)
      {
         sum = sum + i;
      }

You can think of this loop as being equivalent to:

      int sum = 0;
      {
         int i = 0;
         if (i < 3)
         {
            sum = sum + i;   // sum is now 0
         }
         i++;                // i is now 1
         if (i < 3)
         {
            sum = sum + i;   // sum is now 1
         }
         i++;                // i is now 2
         if (i < 3)
         {
            sum = sum + i;   // sum is now 3
         }
         i++;                // i is now 3
         
         // i < 3 is false so the loop ends
      }

Sentinel-Based Input

A common 1020 problem involves repeatedly reading in values from the user until the user types in a special value (called the sentinel). Usually you will have to do something with the values the user types in. For example, suppose you need to write a program that sums all of the values a user types in until the user types in -1.

import java.io.PrintStream;
import java.util.Scanner;

public class ForExample4
{
   public static void main(String[] args)
   {
      PrintStream output = System.out;
      Scanner input = new Scanner(System.in);

      output.println("Enter an integer pressing Enter after each: ");
      final int SENTINEL = -1;
      int sum = 0;
      for (int val = input.nextInt(); val != SENTINEL; val = input.nextInt())
      {
         sum = sum + val;
      }
      output.printf("The sum of the integers is: %d%n", sum);
   }
}

Sentinel-Based Input

      output.println("Enter an integer pressing Enter after each: ");
      final int SENTINEL = -1;
      int sum = 0;
      for (int val = input.nextInt(); val != SENTINEL; val = input.nextInt())
      {
         sum = sum + val;
      }
      output.printf("The sum of the integers is: %d%n", sum);
1. output the message
2. define the sentinel value
3. define the sum

Sentinel-Based Input

      output.println("Enter an integer pressing Enter after each: ");
      final int SENTINEL = -1;
      int sum = 0;
      for (int val = input.nextInt(); val != SENTINEL; val = input.nextInt())
      {
         sum = sum + val;
      }
      output.printf("The sum of the integers is: %d%n", sum);
4.
  a. get a value from the user

Sentinel-Based Input

      output.println("Enter an integer pressing Enter after each: ");
      final int SENTINEL = -1;
      int sum = 0;
      for (int val = input.nextInt(); val != SENTINEL; val = input.nextInt())
      {
         sum = sum + val;
      }
      output.printf("The sum of the integers is: %d%n", sum);
4.
  a. get a value from the user
  b. if the value is not the sentinel then

Sentinel-Based Input

      output.println("Enter an integer pressing Enter after each: ");
      final int SENTINEL = -1;
      int sum = 0;
      for (int val = input.nextInt(); val != SENTINEL; val = input.nextInt())
      {
         sum = sum + val;
      }
      output.printf("The sum of the integers is: %d%n", sum);
4.
  a. get a value from the user
  b. if the value is not the sentinel then
       add the value to the sum

Sentinel-Based Input

      output.println("Enter an integer pressing Enter after each: ");
      final int SENTINEL = -1;
      int sum = 0;
      for (int val = input.nextInt(); val != SENTINEL; val = input.nextInt())
      {
         sum = sum + val;
      }
      output.printf("The sum of the integers is: %d%n", sum);
4.
  a. get a value from the user
  b. if the value is not the sentinel then
       add the value to the sum
       get a value from the user

Sentinel-Based Input

      output.println("Enter an integer pressing Enter after each: ");
      final int SENTINEL = -1;
      int sum = 0;
      for (int val = input.nextInt(); val != SENTINEL; val = input.nextInt())
      {
         sum = sum + val;
      }
      output.printf("The sum of the integers is: %d%n", sum);
4.
  a. get a value from the user
  b. if the value is not the sentinel then
       add the value to the sum
       get a value from the user
       go back to 4b.

Sentinel-Based Input

      output.println("Enter an integer pressing Enter after each: ");
      final int SENTINEL = -1;
      int sum = 0;
      for (int val = input.nextInt(); val != SENTINEL; val = input.nextInt())
      {
         sum = sum + val;
      }
      output.printf("The sum of the integers is: %d%n", sum);
5. output the sum

boolean-Based Loops

Another common 1020 problem is to read in an unknown number of values. In these cases, you need to ask the Scanner object for help. For example, suppose you need to read in an unknown number of pairs of integer values to create Fraction objects.

import java.io.PrintStream;
import java.util.Scanner;
import type.lib.Fraction;

public class ForExample5
{
   public static void main(String[] args)
   {
      PrintStream output = System.out;
      Scanner input = new Scanner(System.in);

      output.println("Enter an even number of integer values: ");
      for (; input.hasNext(); )
      {
         long numer = input.nextLong();
         long denom = input.nextLong();
         Fraction f = new Fraction(numer, denom);
         output.println(f);
      }
   }
}

Note: in Linux you can use Ctrl+d after pressing Enter to tell the Scanner object that there is no more input; in Windows you can use Ctrl+z.