Java Methods while (chapter < 7) chapter++;

Slides:



Advertisements
Similar presentations
Objectives In this chapter, you will learn about:
Advertisements

CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Fundamentals of Python: From First Programs Through Data Structures
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Invitation to Computer Science, Java Version, Second Edition.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
By the end of this session you should be able to...
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Iterative Statements: while, for, do-while Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006.
Algorithms Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin,
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
8.1 8 Algorithms Foundations of Computer Science  Cengage Learning.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
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.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Lecture 4b Repeating With Loops
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 5: Control Structures II
Loop Structures.
Boolean Expressions and if-else Statements
Repetition-Counter control Loop
Introduction to Computer Programming
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Chapter 13 Control Structures
While Statement.
MSIS 655 Advanced Business Applications Programming
Chapter 4: Control Structures I (Selection)
Chapter 13 Control Structures
CS1100 Computational Engineering
Java Methods chapter  4 Algorithms A & AB Object-Oriented Programming
Introduction to Object-Oriented Programming with Java--Wu
Java Programming Loops
Coding Concepts (Basics)
Algorithm Discovery and Design
Chapter 6: Repetition Statements
Algorithm and Ambiguity
Computing Fundamentals
Chapter 4: Control Structures I (Selection)
Chapter8: Statement-Level Control Structures April 9, 2019
Chapter 5: Control Structures II (Repetition)
Java Programming Loops
Basic Concepts of Algorithm
Using C++ Arithmetic Operators and Control Structures
Loops and Iteration CS 21a: Introduction to Computing I
Chapter 13 Control Structures
Presentation transcript:

Java Methods while (chapter < 7) chapter++; Object-Oriented Programming and Data Structures 3rd AP edition Maria Litvin ● Gary Litvin while (chapter < 7) chapter++; Java also has a “for each” loop for traversing lists and other structures. It is explained later, in Chapters 9, 11, and 20. Algorithms and Iterations Copyright © 2015 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

Objectives: Understand general properties of algorithms Get familiar with pseudocode and flowcharts Learn about iterations Understand the semantics and learn the Java syntax for while, for, and do-while loops Learn how to use nested loops Also learn about perfect numbers.

Define Algorithm... Hard to define formally A more or less compact, general, and abstract step-by-step recipe that describes how to perform a certain task or solve a certain problem. Examples: Long division Euclid’s Algorithm for finding the greatest common factor (circa 300 BC) Binary Search (guess-the-number game) Fundamental concepts are often hard to define!

Tools for Describing Algorithms Pseudocode A sequence of statements, more precise notation Not a programming language, no formal syntax Flowcharts Graphical representation of control flow In pseudocode and flowcharts we do not use data types for variables (such as int, double, etc.); in Java we do.

Example: calculate 12 + 22 + ... + n2 Pseudocode Input: n sum  0 k  1 Repeat the following three steps while k  n: sq  k * k sum  sum + sq k  k + 1 Output: sum A  B Set A to the value of B The “repeat” statement is what makes this algorithm compact.

Example (cont’d) Flowchart n Input / output sum  0 k  1 Processing step No Decision k  n ? Yes Flowcharts are pretty much history: they are really not used in software development any more since most software development has switched to OOP. sq  k * k sum  sum + sq k  k + 1 sum

Another Example: Input: pos0, dir0 pos  pos0 dir  dir0 No 1. Start at pos0, facing dir0 2. If wall in front, turn 90º clockwise else go forward 3. If not back to initial position / direction proceed to Step 2 stop pos  pos0 dir  dir0 No Wall in front? Yes Step forward dir  dir + 90º One should specify when a given algorithm applies (preconditions) and its final state (postconditions). What are the preconditions here? “The room is rectangular; the robot is placed next to a wall.” What if the preconditions aren’t satisfied? Infinite loop, the program “hangs.” pos = pos0 and dir = dir0? No Yes Stop

Properties of Algorithms Compactness: an algorithm can use iterations or recursion to repeat the same steps multiple times Generality: the same algorithm applies to any “size” of task or any input values Abstractness: an algorithm does not depend on a particular computer language or platform (although it may depend on the general computing model) Iterations (or recursion) make an algorithm different from a cookbook recipe. In most cookbook instructions, each step is performed once. This works because the chef is slow. But a computer is very fast, billions of times faster than a programmer. If we had to write out separately every instruction that a computer executes, we wouldn’t be able to take advantage of its speed. In non-trivial algorithms, the same sequences of steps are repeated multiple times (but the values of variables are updated at each step).

Properties (cont’d) Input: n General: works for any n sum  0 k  1 Repeat the following three steps while k  n: sq  k * k sum  sum + sq k  k + 1 Output: sum General: works for any n Compact: the same length regardless of n, thanks to iterations  the algorithm repeats the same instructions many times, but with different values of the variables Thus an algorithm can take input parameters. (The “running time” depends on n, of course)

Properties (cont’d) Abstract: Python C/C++ Java int addSquares(int n) { int k, sum = 0; for (k = 1; k <= n; k++) sum += k * k; return sum; } def addSquares(n): s = 0 k = 1 while k <= n: s += k * k k += 1 return s Abstract: Python C/C++ Java public class MyMath { public static int addSquares(int n) int sum = 0; for (int k = 1; k <= n; k++) sum += k * k; return sum; } Algorithms depend on a particular computational model. An algorithm for abacus will be different from an algorithm for computer, and an algorithm for a parallel computer may be different from an algorithm for a conventional von Neumann computer.

Iterations It is essential that a program be able to execute the same set of instructions many times: otherwise a computer would do only as much work as a programmer! Repeating the same code fragment several times is called iterating. Java provides three control statements for iterations (a.k.a. loops): for, while, and do-while. Iterations are what makes a program different from a cookbook recipe.

The while Loop condition is any logical expression, as in if while ( condition ) { statement1; statement2; ... statementN; } The body of the loop Many people prefer to always use braces, as it is easier to add statements to the body of the loop. If the body has only one statement, the braces are optional while ( condition ) statement1;

The while Loop (cont’d) Example: // Returns the smallest n // such that 2^n >= x public static int intLog2 (int x) { int n = 0, p = 1; while ( p < x ) p *= 2; n++; } return n; Initialization Testing “Change” can be increment, decrement, or any other operation. Change

The while Loop (cont’d) Initialization: The variables tested in the condition must be initialized to some values. If the condition is false at the outset, the loop is never entered. Testing: The condition is tested before each iteration. If false, the program continues with the first statement after the loop. Change: At least one of the variables tested in the condition must change within the body of the loop. You can also have something like this: while(true) { ... if (...) return // Or break }

The while Loop (cont’d) Sometimes “change” is implicit in the changed state of a variable: Scanner input = new Scanner(inputFile); while (input.hasNext()) System.out.println ( input.next( ) ); Another example: String stars = ""; while (stars.length() < 50) stars += "*"; Changes the state of input

Loop Invariants A loop invariant is an assertion that is true before the loop and at the end of each iteration. Invariants help us reason about the code. int n = 0, p = 1; while (p < x) { p *= 2; n++; } ... One of the branches of computer science aims at developing techniques for proving the correctness of programs mathematically (rather than testing them). Iterations cause a bit of a problem in this effort, and loop invariants were introduced as a tool to overcome this difficulty. Loop invariant: p = 2n

The for Loop for is a shorthand that combines in one statement initialization, condition, and change: for ( initialization; condition; change ) { statement1; statement2; ... statementN; } “Initialization” and “change” can include several statements, separated by commas.

The for Loop (cont’d) Example: Initialization Testing Change // Returns the smallest n // such that 2^n >= x public static int intLog2 (int x) { int n = 0, p; for (p = 1; p < x; p *= 2) n++; } return n; Initialization Testing It is very easy to replace any for loop with a while loop. Change

The for Loop (cont’d) Java allows you to declare the loop control variable in the for statement itself. For example: for (int k = 0; k < n ; k++) { ... } If you need to use the loop control variable after the loop, then declare it above the loop. The scope of k is the body of the loop, and k is undefined outside the loop

The for Loop (cont’d) “Repeat n times” idiom: or for (int k = 0; k < n ; k++) { ... } Simple idioms make your code instantly understandable to others. for (int count = 1; count <= n ; count++) { ... }

The for Loop (cont’d) Example: n! = 1 * 2 * ... * n /** * Returns 1 * 2 * ... * n, if n >= 1 (and 1 otherwise) */ public static long factorial (int n) { long f = 1; for (int k = 2; k <= n; k++) f *= k; return f; } Factorial grows very rapidly, so you need to use a long.

The do-while Loop do { statement1; statement2; ... statementN; } while ( condition ); The code runs through the body of the loop at least once if condition is false, the next iteration is not executed do-while loops are less common. Always use braces for readability (even if the body has only one statement)

The do-while Loop (cont’d) do-while is convenient when the variables tested in the condition are calculated or read in the body of the loop: String str; do { str = file.readLine(); ... } while (str != null); A do-while loop can be used to get user input that meets certain criteria: int n; do { System.out.print("Enter a positive integer: "); n = kboard.nextInt(); } while n <= 0;

The do-while Loop (cont’d) do-while can be easily avoided: we can usually replace it with a while loop initialized so that it goes through the first iteration: String str = "dummy"; while (str != null) { str = file.readLine(); ... } Some programmers avoid do-while altogether.

break and return in Loops break in a loop instructs the program to immediately quit the current iteration and go to the first statement following the loop. return in a loop instructs the program to immediately quit the current method and return to the calling method. A break or return must be inside an if or an else, otherwise the code after it in the body of the loop will be unreachable. Some people believe a method should have only one return statement. Instead of using a return statement inside the loop, they set a Boolean flag in the loop and test it in the condition; this makes their code cumbersome.

break in Loops Example: int d = n - 1; while (d > 0) { if (n % d == 0) break; d--; } if ( d > 0 ) // if found a divisor ... break quits the loop and continues with the next statement after the loop.

return in Loops Sequential Search method: public int search(String[ ] list, String word) { for (int k = 0; k < list.length; k++) if (list[k].equals (word) return k; } return -1; return quits the method.

Nested Loops A loop within a loop is called nested. // Draw a 5 by 3 grid: for (int x = 0; x < 50; x += 10) { for (int y = 0; y < 30; y += 10) g.fillRect(x, y, 8, 8); } It can be a while loop nested within a for loop, etc.

Nested Loops (cont’d) Braces are optional when the body of the loop(s) is one statement: for (int x = 0; x < 50; x += 10) for (int y = 0; y < 30; y += 10) g.fillRect(x, y, 8, 8); Inner for is the only statement in the outer for’s body One of Maria Litvin’s students called them “nasty loops.” Many programmers prefer to always use braces in loops, especially in nested loops.

Nested Loops (cont’d) Be careful with break: for (int r = 0; r < m.length; r++) { for (int c = 0; c < m[0].length; c++) if (m [ r ][ c ] == 'X' ) break; } ... Breaks out of the inner loop but continues with the outer loop A potential source of inefficiencies or bugs.

“Triangular” Nested Loops “Find duplicates” idiom: The inner lcv starts at the outer lcv’s next value for (int i = 0; i < a.length; i++) { for (int j = i + 1; j < a.length; j++) if (a [ i ].equals(a [ j ]) System.out.println ("Duplicate " + a [ j ] ); } lcv stands for “loop control variable.”

Euclid’s Algorithm Finds the greatest common factor (GCF) of two positive integers Circa 300 BC Euclid wrote Elements, which consists of 13 books. Elements defined the direction of mathematics and the style of mathematical education for over two millennia...

Euclid’s Algorithm (cont’d) a, b Yes a = b? No Yes a > b? No In a quicker version, on each iteration we replace the larger number with the remainder of its division by the smaller number (next slide). a  a - b b  b - a a

Euclid’s Algorithm (cont’d) Iterative version More efficient: public static int gcf (int a, int b) { while (a != b) // a not equal to b if (a > b) a -= b; // subtract b from a else b -= a; // subtract a from b } return a; public static int gcf (int a, int b) { while (a > 0) int temp = b; b = a; a = temp % a; } return b; a, b  b%a, a There is also a recursive version (Chapter 13).

Lab: Perfect Numbers A perfect number is a positive integer equal to the sum of all its divisors (including 1 but excluding the number itself). For example: 28 = 1 + 2 + 4 + 7 + 14 Write a program to find the first four perfect numbers (Java Methods pp. 196-197). This lab is described in the Java Methods textbook.

Lab: Perfect Numbers (cont’d) Euclid showed that if 2n-1 is a prime, then 2n-1(2n-1) is a perfect number. For example: 23-1 = 7 is a prime => 22(23-1) = 28 is a perfect number But it took Euler to prove the converse for even numbers -- see the next slide.

Lab: Perfect Numbers (cont’d) A prime that has a form 2n-1 is called a Mersenne prime. Leonhard Euler 1707-1783 Euler proved that any even perfect number must have that form. Mathematicians still do not know whether any odd perfect numbers exist or not. Marin Mersenne 1588-1648 Write a program to find the first six Mersenne primes and the corresponding perfect numbers.

Lab: Perfect Numbers (cont’d) The largest known Mersenne Prime was found by GIMPS (Great Internet Mersenne Prime Search) participants on January 25, 2013: 257,885,161 - 1. It has 17,425,170 digits. They also claimed the Electronic Frontier Foundation’s $100,000 prize for finding a prime number with more than 10 million digits. The project has also ascertained in 2014 that certain Mersenne Primes are the 43rd and 44th in the sequence. http://www.mersenne.org

Review: Name three iterative control statements in Java. What is the difference between while and do-while? Can any code with a for loop be rewritten with a while loop? Does short-circuit evaluation apply to conditions in loops? Which operators can be used in the “change” part of a for loop? Name three iterative control statements in Java. while, for, do-while What is the difference between while and do-while? while checks the condition before each iteration; if the condition is false at the outset, the while loop is never entered. do-while checks the condition afterward, so it always goes through the body of the loop at least once. Can any code with a for loop be rewritten with a while loop? Yes, easily. Does short-circuit evaluation apply to conditions in loops? Yes, conditions are logical expressions and they are evaluated the same way everywhere in the program. Which operators can be used in the “change” part of a for loop? Any operators can be used, but that part of the loop usually has an assignment operator, a compound assignment, or an increment or decrement operator.

Review (cont’d): Are method calls allowed in a condition in a while loop? Is return allowed in a loop? What is a nested loop? Name a situation where nested loops are used. Can you have nested while loops? Are method calls allowed in a condition in a while loop? Sure: just like in any other expression. Is return allowed in a loop? Yes, it immediately quits the loop and the whole method. What is a nested loop? A loop within a loop. Name a situation where nested loops are used. Finding duplicates in a list; traversing a two-dimensional grid. Can you have nested while loops? Sure, why not?