/**
 * Prints the numbers from 1 to num that are divisible by 3.
 * Demonstrates multiple ways to do this using for loops.
 *
 * @author Zach Tomaszewski
 * @version 10 Oct 2008
 */
public class DivisibleByThree {

  public static void main(String[] args) {

    //get user input
    java.util.Scanner keybd = new java.util.Scanner(System.in);
    System.out.print("Enter a number: ");
    int num = keybd.nextInt();
    //XXX: Demo code, so not bothering with catching exceptions


    //one way to do it
    System.out.println();
    System.out.println("Numbers divisible by 3, from 1 to num:");

    for (int i = 1; i <= num; i++) {
      if (i % 3 == 0) {
        System.out.print(i + " ");
      }
    }
    System.out.println();  //end row of numbers


    //Another way to do it.
    //(I didn't bother looping through 1 and 2 since they will
    // never be divisible by 3 and so will never be output anyway.)
    System.out.println();
    System.out.println("Numbers divis by 3, from 1 to num (again):");

    for (int i = 3; i <= num; i += 3) {
      System.out.print(i + "\t");
    }
    System.out.println();


    /*
     * Print the numbers from 1 to num that are divisible by 3,
     * but print only 5 per line.
     */
    System.out.println();
    System.out.println("Numbers divis by 3, from 1 to num (5 per line):");

    //One way to do this is just print a newline (println()) after
    // each number that is divisible by 5 (or by 15).
    //But here's another way that doesn't depend on the nature of
    //the numbers/data that are being printed:

    int printedThisLine = 0;  //how many numbers I've printed on this line
    for (int i = 3; i <= num; i += 3) {
      System.out.print(i + "\t");
      printedThisLine++;

      if (printedThisLine == 5) {
        //end the line and reset the counter
        System.out.println();
        printedThisLine = 0;
      }
    }
    System.out.println();
  }
}

