Print Page Print Page

CH7 – The for Statement

  1. Create a new class named ForStatement.
  2. Add a method named printTable and a method named printRow to the class.
public static void printTable(int rows){
  for(int i = 1; i <= rows; i = i+1){
    printRow(i, rows);
  }
}
public static void printRow(int n, int cols){
  for(int i = 1; i <= cols; i++){
    System.out.printf("%4d", n * i);
  }
  System.out.println();
}
  1. Add main to the class and call printTable and pass x and y to the method.
public static void main(String[] args){
  ForStatement.printTable(5);
}
  1. Compile and run the program.
$ javac ForStatement.java
$ java ForStatement
   1   2   3   4   5
   2   4   6   8  10
   3   6   9  12  15
   4   8  12  16  20
   5  10  15  20  25

The completed class should appear as follows.

public class ForStatement {
  public static void main(String[] args){
    ForStatement.printTable(5);
    System.out.println();
  }
  public static void printTable(int rows){
    for(int i = 1; i <= rows; i = i+1){
      printRow(i, rows);
    }
  }
  public static void printRow(int n, int cols){
    for(int i = 1; i <= cols; i++){
      System.out.printf("%4d", n * i);
    }
    System.out.println();
  }
}

LearningLad provides another excellent video on for loops.