teaching machines

CS1: Lecture 23 – While Loops Continued

October 25, 2019 by . Filed under cs1, fall 2019, lectures.

Dear students,

Loops turn us into pattern hunters. Behind some complex output is a much simpler machine using repetition. Let’s keep building those repetitive machines today. We’ll keep exploring while loops.

While

Last time we introduced while. Let’s see it at work in a few more programs.

TODO

Here’s your TODO list to complete before we meet again:

See you next class!

Sincerely,

P.S. It’s time for a haiku!

Apocalypse now?
Not according to my count
We’ve got n times yet

P.P.S. Here’s the code we wrote together in class…

Circlererererer.java

package lecture1025.cs145;

public class Circlererererer {
  public static void main(String[] args) {
    int n = 57;
    double delta = 360.0 / n;

    int i = 0;
    while (i < n) {
      double angle = i * delta;
      System.out.printf("(%f,%f)%n", Math.cos(Math.toRadians(angle)), Math.sin(Math.toRadians(angle)));
      i++;
    }
  }
}

Collatz.java

package lecture1025.cs145;

import java.util.Random;

public class Collatz {
  public static void main(String[] args) {
    Random generator = new Random();
    int number = generator.nextInt(100000000);
    System.out.println(number);
    while (number != 1) {
//      System.out.println(number);
      if (number % 2 == 0) {
        number /= 2;
      } else {
        number = 3 * number + 1;
      }
      System.out.println(number);
    }
  }
}

LineNumberererererer.java

package lecture1025.cs145;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class LineNumberererererer {
  public static void main(String[] args) throws FileNotFoundException {
    File file = new File("/Users/johnch/Desktop/limerick.txt");
    Scanner in = new Scanner(file);
    int count = 1;
    while (in.hasNextLine()) {
      System.out.printf("%d: %s%n", count, in.nextLine());
      count++;
    }
    in.close();
  }
}