What can we do with iterations? “Life is just one damn thing after another” – Mark Twain
2 Comparisons b, = can only be used with numbers and characters b Is true greater than false? public class JackandJill { public static void main(String args[]) { String s1 = "Jack went up the hill."; String s2 = "Jack went up the hill."; if (s1 == s2) { System.out.println( "The strings are the same."); }
Comparison else if (s1 != s2) { System.out.println( "The strings are different."); } The output is: The strings are different.
4 Comparison b A Correct Test for String Equality public class JackandJill { public static void main(String args[]) { String s1 = "Jack went up the hill."; String s2 = "Jack went up the hill."; if (s1.equals(s2)) { System.out.println( "The strings are the same."); } else { System.out.println( “They the different."); }
b For every square on the chessboard, I’ll double the wheat debt… How Much Does the King Owe public class CountWheat { public static void main(String args[]) { int current, totalAmount; final int NUM_OF_SQUARES = 64; current = 1; totalAmount = 0; for (int i=1; i <= NUM_OF_SQUARES; i++) { current *= 2; totalAmount += current; System.out.print(totalAmount + “\t ”);
How Much Does the King Owe if (i % 4 == 0) System.out.println(); } The output is: What Happened???
How Much Does the King Owe b Testing for overflow public class CountWheat { public static void main(String args[]) { int current, totalAmount; final int NUM_OF_SQUARES = 64; current = 1; totalAmount = 0; for (int i=1; i <= NUM_OF_SQUARES; i++) { current *= 2; totalAmount += current; if (current <= 0) { System.out.println("Error: Overflow"); break; }
8 System.out.print(totalAmount + “\t ”); if (i % 4 == 0) System.out.println(); } The output is: Error: Overflow How Much Does the King Owe
9 Unstoppable for loop for (long i=Long.MAX_VALUE –2 ; i<= Long.MAX_VALUE; i++) { /*...*/ } b How many times will that for loop execute? Until you kill the process! b It will loop endlessly because I can never get bigger than Long.MAX_VALUE to terminate the loop.
Walls, walls everywhere… b How can you make your way out of a maze ? Exit b Simple! Walk along the walls.
Walls, walls everywhere… public class MazeSolver { public static void main(String args[]) { while (notAtExit) { if (!wallToRight) turnRight(); moveForward(); } else if (!wallAhead) { moveForward(); } else { turnLeft(); }
Walls, walls everywhere… b What does the solution look like?
Palindrome Checkup b Palindromes can be read from either direction: b For example: “Racecar” public class PalindromeTester { // // Tests strings to see if they are palindromes. // public static void main (String[] args) { String str, another = "y"; int left, right; while (another.equalsIgnoreCase("y")) { // allows y or Y System.out.println ("Enter a potential palindrome:"); str = readString();
Palindrome Checkup left = 0; right = str.length() - 1; while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; } System.out.println(); if (left < right) System.out.println ("That string is NOT a palindrome."); else System.out.println ("That string IS a palindrome."); System.out.println(); System.out.print ("Test another palindrome (y/n)? "); another = readString(); }
An Alarm Clock b Develop an alarm clock and set its timer public class AlarmClock { public static void main (String[] args) { int hour, minute, second, alarmHour, alarmMinute, alarmSec; // set the current time do { System.out.print( “ Enter the hour: “ ); hour = readInt(); } while ((hour > HOURS_PER_DAY - 1) || (hour < 0)); do { System.out.print( “ Enter the minutes: “ ); minute = readInt(); } while ((minute > MINUTES_PER_HOUR - 1) || (minute < 0));
do { System.out.print( “ Enter the seconds: “ ); seconds = readInt(); } while ((seconds > SECONDS_PER_MINUTE - 1) || (seconds < 0)); // set the alarm do { System.out.print( “ Enter the alarm hour: “ ); aralmHour = readInt(); } while ((aralmHour > HOURS_PER_DAY-1) || (aralmHour < 0)); do { System.out.print( “ Enter the alarm minutes: “ ); alarmMinute = readInt(); } while ((minute > MINUTES_PER_HOURS-1) || (alarmMinute < 0)); An Alarm Clock
do { System.out.print( “ Enter the alarm seconds: “ ); alarmSeconds = readInt(); } while ((alarmSeconds > SECONDS_PER_MINUTE-1) || (alarmSeconds < 0)); // run the clock while ((hour != alarmHour) || (minute != alarmMinute) || (second != alarmSeconds)) { for (int time=0; time < SECOND; time++); seconds++; if (seconds == SECONDS_PER_MINUTE) { seconds = 0; minute++; }
An Alarm Clock if (minute == MINUTES_PER_HOUR) { minute = 0; hour++; } if (hour == HOURS_PER_DAY) { hour = 0; } // alarm goes off System.out.println( “ Wake up!!! Wake up!!! ” ); }
19 Drawing using loops b Using for loops to draw shapes on the screen public class Drawer { public static void main (String[] args) { for (int i=0; i < 5; i++) { for (int j=0; j < I+1; j++) System.out.print( “ * ” ); System.out.println(); } The output is: ***************
Factorial calculation b Given a number, calculate its factorial b N! = N*(N-1)*(N-2)*….*2*1 public class Factorial { public static void main (String[] args) { long result = 1; int number; do { System.out.print( “ enter a number : “ ); number = readInt(); } while (number < 0); for (int i=number; i > 0; i--) result *= i; System.out.println( “ result is “ + result); }
Fibonacci series + Golden Ratio b Each term is the sum of the two previous ones: b …. public class Fibonacci { public static void main (String[] args) { long lower = 0; long higher = 1; int iterations = readInt(); for (int i=1; i <= iterations; i++) { System.out.print(higher + “ \t “ ); long temp = higher; higher += lower; lower = temp; if (i % 10 == 0) System.out.println(); }
Fibonacci series + Golden Ratio b The Golden Ratio is the ratio of the “last” two terms in this infinite series. b It is supposed to be the ideal proportion in architecture and art, and was used in the design of ancient Greek temples. b If the number of iterations is: 45, the last two terms are: 701,408,733 and 1,134,903,170 and their ratio is: … Close enough for government work.
Calculator b Create the equivalent of a four-function calculator. public class Calculator { public static void main (String[] args) { int operand1, operand2; char operator; while(true) { System.out.print( “ Enter the first operand: “ ); operand1 = readInt(); do { System.out.print( “ Enter the operator: (+, -, *, /) “ ); operator = readChar(); if ((operator == ‘ + ’ ) || (operator == ‘ - ’ ) || (operator == ‘ * ’ ) || (operator == ‘ / ’ )) break; } while (true);
24 Calculator System.out.print( “ Enter the second number: “ ); operator2 = readInt(); switch (operator) { case ‘ + ’ : System.out.println(operator1 + “ + ” + operator2 + “ = “ + (operator1 + operator2)); break; case ‘ - ’ : System.out.println(operator1 + “ - ” + operator2 + “ = “ + (operator1 - operator2)); break; case ‘ * ’ : System.out.println(operator1 + “ * ” + operator2 + “ = “ + (operator1 * operator2)); break;
25 Calculator case ‘ / ’ : System.out.println(operator1 + “ / ” + operator2 + “ = “ + (operator1 / operator2)); break; } System.out.print( “ Another calculation ? ” ); char answer = readChar(); if (answer == ‘ y ’ ) || (answer == ‘ Y ’ ) continue; else // anything buy ‘ y ’ or ‘ Y ’ means no break; }
26 Bank Investment b What will my balance be in X years? public class Investment { public static void main (String[] args) { double amount; double rate; int years; do { System.out.print( “ Enter initial amount : “ ); amount = readDouble(); } while (amount < 0.0); do { System.out.print( “ Enter annual rate : “ ); rate = readDouble(); } while (rate <= 0.0);
27 Bank Investment do { System.out.print( “ Enter number years : “ ); years = readInt(); } while (year < 0); for (int I=0; I < year; I++) amount *= (1.0 + rate); System.out.println( “ After “ + years + “ years, you will have: “ + amount + “ $ ” ); }
switch (month) { case 4: case 6: case 9: case 11: numOfDays = 30; break; case 2: switch (year % 4) { case 0: switch (year % 400) { case 100: case 200: case 300: numOfDays = 28; break; default: numOfDays = 29; } break; default: numOfDays = 28; } break; default: numOfDays = 31; } Y2K