The for loop

  • Syntax of the for-statement in Java:

      for ( initialization ; loop-contuation-condition ; increment )
          one-statement;  // Loop body
    
    or:
    
      for ( initialization ; loop-contuation-condition ; increment )
      { // Loop body
          statement1;
          statement2;
          ...
      } 

  • Effect of the for-statement:

    1. Execute the initialization statement (once)

    2. Check the loop-contuation-condition

    3. If true:   exec (1) the loop-body and (2) increment statement and repeat at 2.
      If false, continue with the next statement in the program

The for loop:    a very commonly used syntax

  • The for-loop is commonly used to:

    • Execute some statements for a certain number of times

  • A very commonly used syntax of the for-loop is:

     int i;  // i is the loop index or loop control variable
    
     for ( i = startValue; i < endValue; i++ )
     {
        statements;
     } 

  • The loop body will be executed for the following list of values of i:

     i = startValue, startValue+1, ..., endValue-1

    We will do an example next...

The for loop:    a very commonly used syntax   example

  • Situation where the for-loop is used:

    • The for-loop is used to repeat a series of actions for a known start value and a known stop value

  • Write a program to sum the numbers:   3 + 4 + 5 + 6 + 7

       public static void main(String[] args) 
       {
          int i;
          int sum = 0;
          
          // Start at 3 and stop before 8
          for ( i = 3; i < 8; i++ )  // i will take on: 3,4,5,6,7
          {
              sum = sum + i;
          }
          
          System.out.print(sum);
       }

DEMO: demo/05-loops/04-for/Summation.java

The for loop    flow chart

     for ( initial-action; loop-continuation-condition; 
                                            actions-after-each-iteration )
     { // Loop body
       statement(s);
     }

  • The flow chart of the for-loop is:

Application of the for loop:   find all divisors of a number

Write a program that reads in a number x and prints out all its divisors:

 Plan:

   Read in x

   We know that:  a divisor of x must be < x

   Try every number that is < x:

   for k = 1, 2, 3, 4, 5, 6, ....., x-1:

       check if k is a divisor of x

       if so: print k 

  

Application of the for loop:   find all divisors of a number

Write a program that reads in a number x and prints out all its divisors:

   public static void main(String[] args) 
   {
      Scanner input = new Scanner(System.in);
      
      int x, k;
      
      System.out.print("Enter a number: ");
      x = input.nextInt();
      
      for ( k = 1; k < x; k++ )
      {
          if ( x%k == 0 )
             System.out.println(k);
      }
   } 

DEMO: demo/05-loops/04-for/Divisor.java