CS18000: Problem Solving and Object-Oriented Programming

Slides:



Advertisements
Similar presentations
CS0004: Introduction to Programming Repetition – Do Loops.
Advertisements

Loops – While, Do, For Repetition Statements Introduction to Arrays
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
JAVA Control Structures: Repetition. Objectives Be able to use a loop to implement a repetitive algorithm Practice, Practice, Practice... Reinforce the.
Introduction to Java. Main() Main method is where the program execution begins. There is only one main Displaying the results: System.out.println (“Hi.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
ECE Application Programming
Lecture 4b Repeating With Loops
REPETITION CONTROL STRUCTURE
Repetition (While-Loop) version]
Python: Control Structures
Chapter 5: Control Structures II
Loop Structures.
User input We’ve seen how to use the standard output buffer
Repetition-Counter control Loop
Java Programming: Guided Learning with Early Objects
Repetition-Sentinel,Flag Loop/Do_While
Chapter 4 – Control Structures Part 1
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Counted Loops.
Lecture 07 More Repetition Richard Gesick.
Selected Topics From Chapter 6 Iteration
Chapter 5: Control Structures II
LOOPS.
Lecture 4B More Repetition Richard Gesick
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Repetition Chapter 6 12/06/16 & 12/07/16 1 1
Arrays, For loop While loop Do while loop
CSS161: Fundamentals of Computing
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan and Vassilis Athitsos University of Texas at Arlington.
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
CS1100 Computational Engineering
Introduction to Object-Oriented Programming with Java--Wu
Module 4 Loops.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 6: Repetition Statements
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Building Java Programs
Chapter 4 - Control Structures: Part 1
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Building Java Programs
Loops CGS3416 Spring 2019 Lecture 7.
Loops and Iteration CS 21a: Introduction to Computing I
ICS103: Programming in C 5: Repetition and Loop Statements
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Looping and Repetition
Presentation transcript:

CS18000: Problem Solving and Object-Oriented Programming Welcome slide for display pre-bell.

Concepts Indefinite Iteration while Loops and Examples Repetition Concepts Indefinite Iteration while Loops and Examples

What’s Missing? Lots of Data You know how to make a decision and execute one statement or another Problems up to now involved working on a fixed set of input or small number of values Next power up: perform repetitive actions Two ways to think about repetition: Perform the same operation on different data Accumulate information over a set of data Examples of the two options: Read lines of text from a file; for each line, say whether it is a palindrome or not. Or, words from a dictionary. Or, walk towards the door. Read numbers from a file and compute (accumulate) their sum. Read lines from a file and create (accumulate) a set of words in the file.

Repetition Concept Repetition broken into two parts Body of code that gets repeatedly executed Condition (boolean) to determine when to stop How to construct the body so that it does something different/useful each time it is run? The state of the computation must change with each iteration (otherwise nothing is done) In the case of reading from a file, eventually the file ends, so the state changes. For walking towards the door, your position changes each time until you reach it. Think inductively: You know by induction that if every time I take a step, I take it closer to the door, eventually I’ll reach the door.

Two Forms of Iteration Indefinite: loop until “done”; no advance knowledge of how many iterations will be required Definite: loop a given number of times; used when the iterations are controlled by a counter or size or limit

Java Repetition Constructs while loop Check a boolean condition If true, execute a block of statements Repeat do-while loop Execute a block of statements If a boolean condition is true, repeat for loop

Problem: Odd or Even Write a program that reads integers from standard input; for each integer print a message indicating “odd” or “even” Stop reading when no more integers Scanner method hasNextInt() returns true if there is another integer available, else returns false Scanner method hasNextInt() returns false at EOF; also returns false if something other than an integer found

Solution: Odd or Even import java.util.Scanner; public class OddOrEven { public static void main(String[] args) { Scanner in = new Scanner(System.in); int number; while (in.hasNextInt()) { number = in.nextInt(); if (number % 2 == 0) System.out.printf("%d is even\n", number); else System.out.printf("%d is odd\n", number); } REFLECTION: When to talk about scope? The “int n” declaration appears inside the loop body and is not “visible” outside of it.

Problem: Summer Read a sequence of integers from the standard input and compute their sum Two problems: How do we know when we’re done? How do we accumulate the sum? Also count the number of values read

Solution: Summer import java.util.Scanner; public class Summer { public static void main(String[] args) { Scanner in = new Scanner(System.in); int number; // number that is input int sum = 0; // sum of values int c = 0; // how many values read while (in.hasNextInt()) { number = in.nextInt(); c = c + 1; sum = sum + number; } System.out.printf("sum of %d values is %d\n", c, sum); Mention c++ and sum += n, to be introduced in a few slides.

Indefinite Iteration Examples Definite Iteration Repetition Indefinite Iteration Examples Definite Iteration

The while Loop while (boolean-expression) { statements; } Test boolean-expression first If true, do statements in body Repeat from 1.

Problem: Palindrome Write a method in class Palindrome boolean isPalindrome(String s) to test if s is a palindrome, a string that reads the same backwards as forwards Approach 1: Use a while loop When to deal with the borderline cases? Need to decide about “” and null, and one-character strings.

Strategy: Palindrome Compare first and last characters; differ? False Strip off first and last characters Repeat until length < 2; return true Test input: “level” (true) “racecar” (true) “henway” (false) “x”, “aba”, “abba” (all true) “” (empty string (true)) null (null value (true)) Remind about String indexing with charAt().

Solution: Palindrome public class Palindrome { boolean isPalindrome(String s) { if (s == null || s.length() <= 1) return true; while (s.length() > 1) { char first = s.charAt(0); char last = s.charAt(s.length() - 1); if (first != last) return false; s = s.substring(1, s.length() - 1); }

Solution: PalindromeTest import junit.framework.TestCase; public class PalindromeTest extends TestCase { public void testIsPalindrome() { Palindrome p = new Palindrome(); assertEquals(true, p.isPalindrome("")); assertEquals(true, p.isPalindrome(null)); assertEquals(true, p.isPalindrome("x")); assertEquals(true, p.isPalindrome("xx")); assertEquals(false, p.isPalindrome("xy")); assertEquals(true, p.isPalindrome("level")); assertEquals(false, p.isPalindrome("henway")); assertEquals(true, p.isPalindrome("racecar")); }

Problem: Reverse Add a method to Palindrome to reverse a String String reverse(String s) to Palindrome to reverse a String isPalindrome could simply be… boolean isPalindrome(String s) { return s.equals(reverse(s)); }

Continue statement while (in.hasNext()) { word = in.next(); if (word.length() != 4) count=count+1; } // is equivalent to…. if (word.length() == 4) continue; else

Break statement while (in.hasNext()) { word = in.next(); if (word.length() == 4) break; else count=count+1; }

Pro Tip: Compound Assignment Common assignment statements: x = x + y; a = a – b; s = s + "\n"; // s is a string Java provides shortcut to save keystrokes: x += y; a -= b; s += "\n"; Available for all (or most) binary operators

Pro Tip 2: Increment/Decrement Operators A refinement for an even more common case: x = x + 1; a = a – 1; Java provides even more keystroke savings: x++; a--; Also: ++x; --a;

Post- and Pre- Increment/Decrement x++ increments x by one, but the expression value is the original x int x = 0; System.out.println(x++); System.out.println(x); Prints 0, then 1 ++x increments x by one, and its value is the new x System.out.println(++x); Prints 1, then 1 x++ and x-- are very common idioms (cf. C++) Life becomes messy if an expression contains multiple pre- and post- increment and decrement operators

Problem: WhileDefinite Problem: Print “hello” 10 times using a while loop Illustrates using a while loop to implement a definite iteration

Solution: WhileDefinite public class WhileDefinite { public static void main(String[] args) { int n = 0; while (n < 10) { System.out.printf("hello (#%d)\n", n); n++; }

The Loop Parts e1. Initialize public class WhileDefinite { public static void main(String[] args) { int n = 0; while (n < 10) { System.out.printf("hello (#%d)\n", n); n++; } for (int n = 0; n < 10; n++) e2. Test e3. Update Remember: computer scientists are compulsive generalizers. Programming language designers are often looking for conciseness.

Definite Iteration: for loop Very general form: for (e1; e2; e3) { statements; } Sequence of actions: Evaluate expression e1 (once only). Evaluate e2. If true, execute statement body. Evaluate e3. Return to step 2.

Common Practices To loop n times, go from 0 to n-1 for (int i = 0; i < n; i++) { statements; } Works well for strings (and arrays): 0-based To print the characters in a String s: String s = "hello there world"; for (int i = 0; i < s.length(); i++) System.out.printf( "s.charAt(%d) = '%c'\n", i, s.charAt(i));

do-while Loop for Loop Nested Loops and Other Examples Repetition do-while Loop for Loop Nested Loops and Other Examples

The do-while Loop do { statements; } while (boolean-expression); Execute statements in body Test boolean-expression If true, repeat from 1

Problem: Prompting the User Write a program, Prompter, that prompts the user for an even number Continue prompting until an even number is provided Show alternate implementation using standard while loop with sentinel

Solution 1: Prompter1 import java.util.Scanner; public class Prompter1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); // Prompt for an even number using do-while... int n; do { System.out.printf("Please enter an even number: "); n = in.nextInt(); } while (n % 2 == 1); System.out.printf("Thank you for entering the even number %d\n", n); }

Solution 2: Prompter2 import java.util.Scanner; public class Prompter2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = 0; // Prompt for an even number with while, using sentinel... boolean noEvenYet = true; while (noEvenYet) { System.out.printf("Please enter an even number: "); n = in.nextInt(); if (n % 2 == 0) noEvenYet = false; } System.out.printf("Thank you for entering the even number %d\n", n);

Problem: Palindrome (Redone) Write a method in class Palindrome boolean isPalindrome(String s) to test if s is a palindrome (reads the same backwards as forward) Approach 2: Use a for loop

Palindrome: Strategy Iterate through the first half of the string Compare current character to corresponding character at other end of string Consider table of indexes i and j for “racecar” Find pattern, generalize to solution R A C E C A R 0 1 2 3 4 5 6 I j sum is constant 0 6 6 1 5 6 2 4 6 J = 6 – I = s.length() – 1 – I

Palindrome: Solution boolean isPalindrome(String s) { if (s == null) return true; for (int i = 0; i < s.length() / 2; i++) if (s.charAt(i) != s.charAt(s.length() - 1 - i)) return false; } Could also manage a second loop variable, j; starts at s.length() – 1 and decrements. Try it!

Common Mistakes Infinite loop Almost infinite loop Fencepost errors Skipped loops Misplaced semicolons

Infinite Loop public class InfiniteLoop { public static void main(String[] args) { int n = 1; while (n < 100) { System.out.printf("n = %d\n", n); // forgot to increment n }

Almost Infinite Loop public class AlmostInfiniteLoop { public static void main(String[] args) { // count down to blast off for (int i = 10; i > 0; i++) System.out.printf("%d\n", i); System.out.printf("BLAST OFF!\n"); } Doesn’t exit until integer wrap around (overflow) and the value of goes negative. This program, writing output to a file, took just over 239 minutes (of real time; 110 minutes user time and 126 minutes system time) on my office iMac. About 4 hours to wrap around. The output file was 22.5 GB. 2147483639 2147483640 2147483641 2147483642 2147483643 2147483644 2147483645 2147483646 2147483647 BLAST OFF!

Fencepost Error public class FencePostError { public static void main(String[] args) { for (int i = 0; i <= 5; i++) System.out.printf( "print this line 5 times (%d)\n", i); }

Skipped Loop import java.util.Scanner; public class SkippedLoop { public static void main(String[] args) { Scanner in = new Scanner(System.in); int number = 0; int sum = 0; // read ints from user until zero, then print sum while (number > 0) { sum += number; number = in.nextInt(); } System.out.printf("sum = %d\n", sum);

Misplaced Semicolon public class MisplacedSemicolon { public static void main(String[] args) { int i = 10; while (--i >= 0); { System.out.printf("message #%d\n", i); }

Nested Loops Just like you can nest if statements You can also nest loops Inner loop is run completely for each iteration of outer loop: public class Nested { public static void main(String[] args) { for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) System.out.printf("i = %d, j = %d\n", i, j); }

Problem: Draw Divisor Pattern Print an nxn table The entry at row i and column j has an * if i divides j or j divides I Example for n == 5 1 2 3 4 5 1 * * * * * 2 * * * 3 * * 4 * * * 5 * *

Solution: Draw Divisor Pattern public class DivisorPattern { public static void main(String[] args) { int n = 5; System.out.printf(" "); for (int i = 1; i <= n; i++) System.out.printf("%3d", i); System.out.printf("\n"); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (i % j == 0 || j % i == 0) System.out.printf(" *"); else System.out.printf(" "); }

Problem: convertToBinary Create a class Converter with method String convertToBinary(int n) that converts n to binary equivalent, as a String of 0s and 1s Use while loop Do this problem if there is time.

Solution: convertToBinary public class Converter { String convertToBinary(int n) { String result = ""; // handle special cases... if (n < 0) return null; // failure if (n == 0) return "0"; // loop while n > 0, accumulating a bit and dividing by 2... while (n > 0) { if (n % 2 == 0) result = "0" + result; else result = "1" + result; n = n / 2; } return result;

Problem: Collatz Implement the following algorithm to generate a sequence of integers starting at n (n > 0): While n is greater than 1: If n is odd, multiply by 3 and add 1 If n is even, divide by 2 Repeat with the new value of n Count and return the number of values in the sequence (including first (n) and last (1)) Use class name Collatz And method “int count(int n)” Sample sequence for n = 22: 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 Start by printing the Collatz sequence, then count the length. A generalization of the Collatz problem is algorithmically undecidable.

Solution: Collatz public class Collatz { int count(int n) { int c = 1; while (n > 1) { c++; if (n % 2 == 0) n /= 2; else n = 3 * n + 1; } return c; public static void main(String[] args) { Collatz c = new Collatz(); System.out.println(c.count(22)); System.out.println(c.count(1)); System.out.println(c.count(1000));