what can we do with iterations? “life is just one damn thing after another” – mark twain

28
What can we do with What can we do with iterations? iterations? Life is just one damn thing after another” – Mark Life is just one damn thing after another” – Mark Twain Twain

Upload: moris-elliott

Post on 17-Dec-2015

222 views

Category:

Documents


4 download

TRANSCRIPT

What can we do with iterations?What can we do with iterations?““Life is just one damn thing after another” – Mark Twain Life is just one damn thing after another” – Mark Twain

2

ComparisonsComparisons

<, >, <= and >= can only be used with numbers and <, >, <= and >= can only be used with numbers and characterscharacters

Is true greater than false? 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.");

}

ComparisonComparison

else if (s1 != s2) {

System.out.println( "The strings are different.");

}

}

}

The output is:The output is:

The strings are different.The strings are different.

4

ComparisonComparison

A Correct Test for String EqualityA 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."); } }}

For every square on the chessboard, I’ll double the wheat For every square on the chessboard, I’ll double the wheat debt…debt…

How Much Does the King How Much Does the King OweOwe

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 How Much Does the King OweOwe

if (i % 4 == 0) System.out.println(); } }}

The output is:The output is:22 6 14 30 6 14 30

6262 126 254 510 126 254 510

10221022 2046 4094 8190 2046 4094 8190

1638216382 32766 65534 131070 32766 65534 131070

262142 524286 1048574 2097150 262142 524286 1048574 2097150

4194302 8388606 16777214 33554430 4194302 8388606 16777214 33554430

67108862 134217726 268435454 536870910 67108862 134217726 268435454 536870910

1073741822 2147483646 -2 -2 1073741822 2147483646 -2 -2

-2 -2 -2 -2-2 -2 -2 -2

-2 -2 -2 -2-2 -2 -2 -2

What Happened???

How Much Does the King How Much Does the King OweOwe

Testing for overflowTesting 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:The output is:22 6 14 30 6 14 30

6262 126 254 510 126 254 510

10221022 2046 4094 8190 2046 4094 8190

1638216382 32766 65534 131070 32766 65534 131070

262142 524286 1048574 2097150 262142 524286 1048574 2097150

4194302 8388606 16777214 33554430 4194302 8388606 16777214 33554430

67108862 134217726 268435454 536870910 67108862 134217726 268435454 536870910

1073741822 2147483646 Error: Overflow1073741822 2147483646 Error: Overflow

How Much Does the King How Much Does the King OweOwe

9

Unstoppable for loopUnstoppable for loop

for (long i=Long.MAX_VALUE –2 ; i<= Long.MAX_VALUE; i++) { /* ...*/ }

How many times will that for loop execute? Until you kill the process!How many times will that for loop execute? Until you kill the process!

It will loop endlessly because I can never get bigger than It will loop endlessly because I can never get bigger than Long.MAX_VALUE to terminate the loop.Long.MAX_VALUE to terminate the loop.

Walls, walls everywhere…Walls, walls everywhere…

How can you make your way out of a maze ?How can you make your way out of a maze ?

Exit

Simple! Walk along the walls.Simple! Walk along the walls.

Walls, walls everywhere…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…Walls, walls everywhere…

What does the solution look like?What does the solution look like?

Palindrome CheckupPalindrome Checkup

Palindromes can be read from either direction:Palindromes can be read from either direction: For example: “Racecar”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 CheckupPalindrome 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 ClockAn Alarm Clock

Develop an alarm clock and set its timerDevelop 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 ClockAn Alarm Clock

An Alarm ClockAn 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 ClockAn 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 loopsDrawing using loops

Using for loops to draw shapes on the screenUsing 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:The output is:******************************

Factorial calculationFactorial calculation

Given a number, calculate its factorialGiven a number, calculate its factorial N! = N*(N-1)*(N-2)*….*2*1N! = 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 RatioFibonacci series + Golden Ratio Each term is the sum of the two previous ones:Each term is the sum of the two previous ones:

0 1 1 2 3 5 8 13 21 34 55….0 1 1 2 3 5 8 13 21 34 55….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 RatioFibonacci series + Golden Ratio

The Golden Ratio is the ratio of the “last” two terms in this infinite The Golden Ratio is the ratio of the “last” two terms in this infinite series.series.

It is supposed to be the ideal proportion in architecture and art, and It is supposed to be the ideal proportion in architecture and art, and was used in the design of ancient Greek temples.was used in the design of ancient Greek temples.

If the number of iterations is: 45, the last two terms are: 701,408,733 If the number of iterations is: 45, the last two terms are: 701,408,733 and 1,134,903,170 and their ratio is: 0.618034… Close enough for and 1,134,903,170 and their ratio is: 0.618034… Close enough for government work.government work.

CalculatorCalculator

Create the equivalent of a four-function calculator.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

CalculatorCalculator

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

CalculatorCalculator

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 InvestmentBank Investment

What will my balance be in X years?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 InvestmentBank 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;}

Y2KY2K