Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Java Methods while (chapter < 7) chapter++;"— Presentation transcript:

1 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.

2 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.

3 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!

4 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.

5 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.

6 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

7 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

8 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).

9 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)

10 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.

11 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.

12 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;

13 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

14 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 }

15 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

16 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

17 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.

18 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

19 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

20 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++) { ... }

21 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.

22 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)

23 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;

24 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.

25 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.

26 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.

27 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.

28 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.

29 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.

30 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.

31 “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.”

32 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...

33 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

34 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).

35 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 = Write a program to find the first four perfect numbers (Java Methods pp ). This lab is described in the Java Methods textbook.

36 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.

37 Lab: Perfect Numbers (cont’d)
A prime that has a form 2n-1 is called a Mersenne prime. Leonhard Euler 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 Write a program to find the first six Mersenne primes and the corresponding perfect numbers.

38 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, 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.

39 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.

40 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?


Download ppt "Java Methods while (chapter < 7) chapter++;"

Similar presentations


Ads by Google