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

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Repetition Statements Recitation – 02/20/2009 CS 180 Department of Computer Science, Purdue University.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
Computer Science A 4 13/3. Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Iteration and Loop Statements Horstmann Chapter 7 Loop statements control repeated execution of a block of statements Each time the statements in the block.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
INF 523Q Chapter 3: Program Statements (Examples).
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Laboratory Study October, The very first example, traditional "Hello World!" program: public class first { public static void main (String[ ]
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 Conditionals and Loops Now we will examine programming statements.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Chapter 7 Recursion Recursive methods Recursion in two- dimensional grids Recursive helper method Analysis of recursive algorithms.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
Flow of Control Part 1: Selection
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Sahar Mosleh California State University San MarcosPage 1 Program Control Statement.
Java Basics Hussein Suleman March 2007 UCT Department of Computer Science Computer Science 1015F.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
More loops while and do-while. Recall the for loop in general for (initialization; boolean_expression; update) { }
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Decisions, Decisions, Decisions Conditional Statements In Java.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
FOR LOOP WALK THROUGH public class NestedFor { public static void main(String [] args) { for (int i = 1; i
1 Input/Output. 2 In Java input and output take place through I/O streams – An I/O stream represents an input source or output destination – Streams support.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Application development with Java Lecture 6 Rina Zviel-Girshin.
Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare.
 CSC111 Quick Revision. Problem Write a java code that read a string, then show a list of options to the user to select from them, where:  L to print.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
COS 312 DAY 5 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 2 Posted – Due Feb 22 prior to class – Any issues? Assignment 3 will be posted soon Capstones.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 4: Control Structures I
Recursion -- Introduction
Chapter 4: Control Structures I
Introduction to programming in java
Chapter 6 More Conditionals and Loops
Repetition-Sentinel,Flag Loop/Do_While
Counted Loops.
Selected Topics From Chapter 6 Iteration
Examples of class: Using System.in.read ()
Chapter 4: Control Structures I
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Control Structure Chapter 3.
CIS 110: Introduction to Computer Programming
Repetition Statements
Outline Boolean Expressions The if Statement Comparing Data
Review of Previous Lesson
Presentation transcript:

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