teaching machines

CS 145 Lecture 8 – Loops

February 17, 2012 by . Filed under cs145, lectures, spring 2012.

Agenda

Code

ForFun.java

package preexam1;

public class ForFun {
  public static void main(String[] args) {
    for (int i = 0; i < 3; i = i + 1) {
      System.out.println("Bye, Patrick!");
    }
    
    int sum = 0;
    for (int i = 1; i <= 100; i = i + 1) {
//      System.out.println(i);
      sum = sum + i;
    }
    System.out.println(sum);
  }
}

Acrostic.java

package preexam1;

import java.util.Scanner;

public class Acrostic {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Theme: ");
    String theme = in.nextLine();
    
    int letterCount = theme.length();
    for (int i = 0; i < letterCount; i = i + 1) {
      System.out.print(theme.charAt(i));
      in.nextLine();
    }
  }
}

Spelunking.java

package preexam1;

public class Spelunking {

  public static String getStatusBar(int n) {
    String stars = "";
//    for (int i = 0; i < n; i = i + 1) {
    for (int i = 0; i < n; ++i) {
      stars = stars + "*";
    }
    return stars;
  }
}

Haiku

We all have work dreams.
Programmers wake up in loops–
and piles of money.