1.3 Conditionals and Loops Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · October.

Slides:



Advertisements
Similar presentations
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Advertisements

8-May-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Topic 03 Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
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.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Loops II Lecture 13, Thu Feb
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
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.
Java Programming: From the Ground Up
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
1 Debugging. 2 A Lot of Time is Spent Debugging Programs Debugging. Cyclic process of editing, compiling, and fixing errors. n Always a logical explanation.
Chapter 5 Loops.
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.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
CS 112 Introduction to Programming Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
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.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
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
2.1 Functions Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · 9/10/08 9/10/08.
Repetition Statements while and do while loops
Chapter 5: Control Structures II
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Recap of Functions. Functions in Java f x y z f (x, y, z) Input Output Algorithm Allows you to clearly separate the tasks in a program. Enables reuse.
CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © Your First Java.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Introduction to Loops Iteration Repetition Counting Loops Also known as.
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.
1.2 Built-in Types of Data Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · December.
School of Computer Science & Information Technology G6DICP - Lecture 6 Errors, bugs and debugging.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
1.3 Conditionals and Loops Copyright 2004, FoxTrot by Bill Amend
The for loop.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Application development with Java Lecture 6 Rina Zviel-Girshin.
CompSci 100e2.1 1 N-Body Simulation l Applications to astrophysics.  Orbits of solar system bodies.  Stellar dynamics at the galactic center.  Stellar.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
COMP Loop Statements Yi Hong May 21, 2015.
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.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
2.4 A Case Study: Percolation Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Loops.
Chapter 5: Control Structures II
CiS 260: App Dev I Chapter 4: Control Structures II.
CSS161: Fundamentals of Computing
Outline Altering flow of control Boolean expressions
Data types, assignment statements, and math functions allow you to compute You write a sequence of statements that tell the computer what needs to be done.
Chapter 4 Selection.
Building Java Programs
Building Java Programs
Repetition Statements
Introduction to Computer Science I.
Presentation transcript:

1.3 Conditionals and Loops Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · October 4, :15 AM

2 A Foundation for Programming objects functions and modules graphics, sound, and image I/O arrays conditionals and loops Mathtext I/O assignment statementsprimitive data types equivalent to a calculator any program you might want to write

3 A Foundation for Programming objects functions and modules graphics, sound, and image I/O arrays any program you might want to write to infinity and beyond! conditionals and loops Mathtext I/O assignment statementsprimitive data types

4 Control Flow Control flow. n Sequence of statements that are actually executed in a program. n Conditionals and loops: enable us to choreograph control flow. statement 2 statement 1 statement 4 statement 3 boolean 2 true false statement 2 boolean 1 statement 3 false statement 1 true straight-line control flow control flow with conditionals and loops

Conditionals

6 If Statement The if statement. A common branching structure. Check boolean condition. If true, execute some statements. If false, execute other statements. if ( boolean expression ) { statement T ; } else { statement F ; } can be any sequence of statements statement T true false boolean expression statement F

7 If Statement The if statement. A common branching structure. Check boolean condition. If true, execute some statements. If false, execute other statements.

8 If Statement Ex. Take different action depending on value of variable. public class Flip { public static void main(String[] args) { if (Math.random() < 0.5) System.out.println("Heads"); elseMath.random() < 0.5) System.out.println("Tails"); }

9 If Statement Examples

10 The While Loop

11 While Loop The while loop. A common repetition structure. n Check a boolean expression. n Execute a sequence of statements. n Repeat. while ( boolean expression ) { statement 1 ; statement 2 ; } statement 1 true false boolean expression statement 2 loop body loop continuation condition

12 While Loops: Powers of Two Ex. Print first n powers of 2. Increment i from 1 to n. Double v each time. Click for demo int i = 0; int v = 1; while (i <= N) { System.out.println(v); i = i + 1; v = 2 * v; } % java Powers iv true i <= N true true false n = 6

13 Powers of Two public class PowersOfTwo { public static void main(String[] args) { // last power of two to print int N = Integer.parseInt(args[0]); int i = 0; // loop control counter int v = 1; // current power of two while (i <= N) { System.out.println(v); i = i + 1; v = 2 * v; } % java PowersOfTwo % java PowersOfTwo print ith power of two

14 While Loop Challenge Q. Anything wrong with the following code for printing powers of 2? int i = 0; int v = 1; while (i <= N) System.out.println(v); i = i + 1; v = 2 * v;

15 While Loop Challenge Q. Anything wrong with the following code for printing powers of 2? A. Need curly braces around statements in while loop; otherwise it enters an infinite loop, printing 1s. Moment of panic. How to stop infinite loop? int i = 0; int v = 1; while (i <= N) System.out.println(v); i = i + 1; v = 2 * v;

16 A Wonderful Square Root Copyright 2004, Sidney Harris, % java Sqrt

17 While Loops: Square Root Q. How might we implement Math.sqrt() ? A. To compute the square root of c: n Initialize t 0 = c. n Repeat until t i = c / t i, up to desired precision: set t i+1 to be the average of t i and c / t i. computing the square root of 2

18 public class Sqrt { public static void main(String[] args) { double EPS = 1E-15; double c = Double.parseDouble(args[0]); double t = c; while (Math.abs(t - c/t) > t*EPS) { t = (c/t + t) / 2.0; } System.out.println(t); } % java Sqrt error tolerance 15 decimal digits of accuracy in 5 iterations While Loops: Square Root Q. How might we implement Math.sqrt() ? A. To compute the square root of c: n Initialize t 0 = c. n Repeat until t i = c / t i, up to desired precision: set t i+1 to be the average of t i and c / t i.

19 Newton-Raphson Method Square root method explained. n Goal: find root of function f(x). n Start with estimate t 0. n Draw line tangent to curve at x= t i. n Set t i+1 to be x-coordinate where line hits x-axis. n Repeat until desired precision. f(x) = x 2 - c to compute  c

20 The For Loop Copyright 2004, FoxTrot by Bill Amend

21 For Loops The for loop. Another common repetition structure. n Execute initialization statement. n Check boolean expression. n Execute sequence of statements. n Execute increment statement. n Repeat. for ( init ; boolean expression ; increment ) { statement 1 ; statement 2 ; } statement 1 true false boolean expression statement 2 init increment body loop continuation condition

22 Anatomy of a For Loop Q. What does it print? A.

23 For Loops: Subdivisions of a Ruler Create subdivision of a ruler. Initialize ruler to empty string. For each value i from 1 to N : sandwich two copies of ruler on either side of i. public class Ruler { public static void main(String[] args) { int N = Integer.parseInt(args[0]); String ruler = " "; for (int i = 1; i <= N; i++) { ruler = ruler + i + ruler; } System.out.println(ruler); } 1" 1 " iruler 2" " 3" " "

24 % java Ruler 1 1 % java Ruler % java Ruler % java Ruler % java Ruler % java Ruler 100 Exception in thread "main" java.lang.OutOfMemoryError For Loops: Subdivisions of a Ruler Observation. Loops can produce a huge amount of output!

25 Loop Examples

26 Nesting

27 Nesting Conditionals and Loops Conditionals enable you to do one of 2 n sequences of operations with n lines. More sophisticated programs. n Nest conditionals within conditionals. n Nest loops within loops. n Nest conditionals within loops within loops. if (a0 > 0) System.out.print(0); if (a1 > 0) System.out.print(1); if (a2 > 0) System.out.print(2); if (a3 > 0) System.out.print(3); if (a4 > 0) System.out.print(4); if (a5 > 0) System.out.print(5); if (a6 > 0) System.out.print(6); if (a7 > 0) System.out.print(7); if (a8 > 0) System.out.print(8); if (a9 > 0) System.out.print(9); Loops enable you to do an operation n times using only 2 lines of code. double sum = 0.0; for (int i = 1; i <= 1024; i++) sum = sum / i; 2 10 = 1024 possible results, depending on input computes 1/1 + 1/ /1024

28 Nested If Statements Ex. Pay a certain tax rate depending on income level. double rate; if (income < 47450) rate = 0.22; else if (income < ) rate = 0.25; else if (income < ) rate = 0.28; else if (income < ) rate = 0.33; else if (income < ) rate = 0.35; graduated income tax calculation ,45022% IncomeRate 47,450 – 114,65025% 114,650 – 174,70028% 174,700 – 311,95033% 311, % 5 mutually exclusive alternatives

29 Nested If Statements is shorthand for Be careful when nesting if-else statements (see Q+A p. 75). if (income < 47450) rate = 0.22; else if (income < ) rate = 0.25; else if (income < ) rate = 0.28; else if (income < ) rate = 0.33; else if (income < ) rate = 0.35; if (income < 47450) rate = 0.22; else { if (income < ) rate = 0.25; else { if (income < ) rate = 0.28; else { if (income < ) rate = 0.33; else if (income < ) rate = 0.35; }

30 Nested If Statement Challenge Q. Anything wrong with the following for income tax calculation? double rate = 0.35; if (income < 47450) rate = 0.22; if (income < ) rate = 0.25; if (income < ) rate = 0.28; if (income < ) rate = 0.33; wrong graduated income tax calculation ,45022% IncomeRate 47,450 – 114,65025% 114,650 – 174,70028% 174,700 – 311,95033% 311, %

31 Monte Carlo Simulation

32 Gambler's Ruin Gambler's ruin. Gambler starts with $stake and places $1 fair bets until going broke or reaching $goal. n What are the chances of winning? n How many bets will it take? One approach. Monte Carlo simulation. n Flip digital coins and see what happens. n Repeat and compute statistics.

33 public class Gambler { public static void main(String[] args) { int stake = Integer.parseInt(args[0]); int goal = Integer.parseInt(args[1]); int trials = Integer.parseInt(args[2]); int wins = 0; System.out.println(wins + " wins of " + trials); } // repeat experiment N times for (int i = 0; i < trials; i++) { } // do one gambler's ruin experiment int t = stake; while (t > 0 && t < goal) { } if (t == goal) wins++; // flip coin and update if (Math.random() < 0.5) t++; else t--; Gambler's Ruin

34 Digression: Simulation and Analysis Fact. Probability of winning = stake  goal. Fact. Expected number of bets = stake  desired gain. Ex. 20% chance of turning $500 into $2500, but expect to make one million $1 bets. Remark. Both facts can be proved mathematically; for more complex scenarios, computer simulation is often the best plan of attack. % java Gambler wins of 1000 % java Gambler wins of 1000 % java Gambler wins of 1000 stake goal trials after a substantial wait…. 500/2500 = 20% 500 * ( ) = 1 million

35 Control Flow Summary Control flow. n Sequence of statements that are actually executed in a program. n Conditionals and loops: enables us to choreograph the control flow. Straight-line programs All statements are executed in the order given. Conditionals Certain statements are executed depending on the values of certain variables. if if-else Loops Certain statements are executed repeatedly until certain conditions are met. while for do-while Control FlowDescriptionExamples 1.4

36 Program Development Admiral Grace Murray Hopper Ada Lovelace

37 95% of Program Development Program development. Creating a program and putting it to good use. Def. A bug is a mistake in a computer program. Programming is primarily a process of finding and fixing bugs. Good news. Can use computer to test program. Bad news. Cannot use computer to automatically find all bugs.

38 95% of Program Development Debugging. Cyclic process of editing, compiling, and fixing errors. n Always a logical explanation. n What would the machine do? n Explain it to the teddy bear. You will make many mistakes as you write programs. It's normal. “ If I had eight hours to chop down a tree, I would spend six hours sharpening an axe. ” — Abraham Lincoln “As soon as we started programming, we found out to our surprise that it wasn't as easy to get programs right as we had thought. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs. ” — Maurice Wilkes

39 Debugging Example Factor. Given an integer N > 1, compute its prime factorization. Application. Break RSA cryptosystem (factor 200-digit numbers). 3,757,208 = 2 3  7  13 2  = 2  = 17 11,111,111,111,111,111 = 2,071,723  5,363,222,357

40 Debugging Example Factor. Given an integer N, compute its prime factorization. Brute-force algorithm. For each putative factor i = 2, 3, 4, …, check if N is a multiple of i, and if so, divide it out /8

41 Debugging: 95% of Program Development Programming. A process of finding and fixing mistakes. n Compiler error messages help locate syntax errors. n Run program to find semantic and performance errors. public class Factors { public static void main(String[] args) { long N = Long.parseLong(args[0]) for (i = 0; i < N; i++) { while (N % i == 0) System.out.print(i + " ") N = N / i } this program has many bugs! as long as i is a factor, divide it out check if i is a factor

42 public class Factors { public static void main(String[] args) { long N = Long.parseLong(args[0]) for (i = 0; i < N; i++) { while (N % i == 0) System.out.print(i + " ") N = N / i } % javac Factors.java Factors.java:6: ';' expected for (i = 2; i < N; i++) ^ 1 error Debugging: Syntax Errors Syntax error. Illegal Java program. n Compiler error messages help locate problem. Goal: no errors and a file named Factors.class. the first error

43 public class Factors { public static void main(String[] args) { long N = Long.parseLong(args[0]); for (int i = 0; i < N; i++) { while (N % i == 0) System.out.print(i + " "); N = N / i; } Debugging: Syntax Errors Syntax error. Illegal Java program. n Compiler error messages help locate problem. Goal: no errors and a file named Factors.class. syntax (compile-time) errors need to declare variable i need terminating semicolons

44 public class Factors { public static void main(String[] args) { long N = Long.parseLong(args[0]); for (int i = 0; i < N; i++) { while (N % i == 0) System.out.print(i + " "); N = N / i; } Debugging: Semantic Errors Semantic error. Legal but wrong Java program. n Run program to identify problem. n Add print statements if needed to produce trace. % javac Factors.java % java Factors Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Factors.main(Factors.java:5) oops, no argument

45 public class Factors { public static void main(String[] args) { long N = Long.parseLong(args[0]); for (int i = 0; i < N; i++) { while (N % i == 0) System.out.print(i + " "); N = N / i; } Debugging: Semantic Errors Semantic error. Legal but wrong Java program. n Run program to identify problem. n Add print statements if needed to produce trace. % javac Factors.java % java Factors 98 Exception in thread "main" java.lang.ArithmeticExeption: / by zero at Factors.main(Factors.java:8) need to start at 2 because 0 and 1 cannot be factors

46 public class Factors { public static void main(String[] args) { long N = Long.parseLong(args[0]); for (int i = 2; i < N; i++) { while (N % i == 0) System.out.print(i + " "); N = N / i; } Debugging: Semantic Errors Semantic error. Legal but wrong Java program. n Run program to identify problem. n Add print statements if needed to produce trace. % javac Factors.java % java Factors … infinite loop! indents do not imply braces

47 public class Factors { public static void main(String[] args) { long N = Long.parseLong(args[0]); for (int i = 2; i < N; i++) { while (N % i == 0) { System.out.print(i + " "); N = N / i; } Debugging: The Beat Goes On Success. Program factors 98 = 2  7 2. n But that doesn't mean it works for all inputs. n Add trace to find and fix (minor) problems. % java Factors % % java Factors 5 % java Factors 6 2 % need newline ??? no output ??? missing the 3

48 public class Factors { public static void main(String[] args) { long N = Long.parseLong(args[0]); for (int i = 2; i < N; i++) { while (N % i == 0) { System.out.println(i + " "); N = N / i; } System.out.println("TRACE: " + i + " " + N); } Debugging: The Beat Goes On Success. Program factors 98 = 2  7 2. n But that doesn't mean it works for all inputs. n Add trace to find and fix (minor) problems. % java Factors 5 TRACE 2 5 TRACE 3 5 TRACE 4 5 % java Factors 6 2 TRACE 2 3 Aha! Print out N after for loop (if it is not 1)

49 public class Factors { public static void main(String[] args) { long N = Long.parseLong(args[0]); for (int i = 2; i < N; i++) { while (N % i == 0) { System.out.print(i + " "); N = N / i; } if (N > 1) System.out.println(N); else System.out.println(); } Success. Program seems to work. Debugging: Success? "corner case" % java Factors 5 5 % java Factors % java Factors % java Factors

50 Performance error. Correct program, but too slow. public class Factors { public static void main(String[] args) { long N = Long.parseLong(args[0]); for (int i = 2; i < N; i++) { while (N % i == 0) { System.out.print(i + " "); N = N / i; } if (N > 1) System.out.println(N); else System.out.println(); } Debugging: Performance Error % java Factors % java Factors % java Factors % java Factors very long wait (with a surprise ending)

51 public class Factors { public static void main(String[] args) { long N = Long.parseLong(args[0]); for (int i = 2; i <= N/i; i++) { while (N % i == 0) { System.out.print(i + " "); N = N / i; } if (N > 1) System.out.println(N); else System.out.println(); } Performance error. Correct program, but too slow. Solution. Improve or change underlying algorithm. Debugging: Performance Error % java Factors % java Factors % java Factors % java Factors fixes performance error: if N has a factor, it has one less than or equal to its square root

52 Q. How large an integer can I factor? Note. Can't break RSA this way (experts are still trying). % java Factors % java Factors Program Development: Analysis † estimated largest factor 3instant digits (i <= N) seconds 977 seconds 1221 hours † instant (i*i <= N) instant 0.16 seconds years † millennia † 2.7 seconds 92 seconds after a few minutes of computing….

53 Debugging Programming. A process of finding and fixing mistakes. 1. Create the program. 2. Compile it. Compiler says: That’s not a legal program. Back to step 1 to fix syntax errors. 3. Execute it. Result is bizarrely (or subtly) wrong. Back to step 1 to fix semantic errors. 4. Enjoy the satisfaction of a working program! 5. Too slow? Back to step 1 to try a different algorithm.

54 U.S.S. Grace Murray Hopper

Extra Slides

56 Oblivious Sorting Sort. Read in 3 integers and rearrange them in ascending order. Puzzle 1. Sort 4 integers with 5 compare-exchanges. Puzzle 2. Sort 6 integers with 12. public class Sort3 { public static void main(String[] args) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = Integer.parseInt(args[2]); if (b > c) { int t = b; b = c; c = t; } if (a > b) { int t = a; a = b; b = t; } if (b > c) { int t = b; b = c; c = t; } System.out.println(a + " " + b + " " + c); } read in 3 integers from command-line swap b and c % java Sort % java Sort swap a and b swap b and c

57 Do-While Loop The do-while loop. A less common repetition structure. n Execute sequence of statements. n Check loop-continuation condition. n Repeat. do { statement 1; statement 2; } while (boolean expression); do-while loop syntax statement 2 true false boolean expression statement 1

58 Do-While Loop Ex. Find a point (x, y) that is uniformly distributed in unit disc. n Pick a random point in unit square. n Check if point is also in unit disc. n Repeat. do { x = 2.0 * Math.random() - 1.0; y = 2.0 * Math.random() - 1.0; } while (x*x + y*y > 1.0); (1, 1) (0, 0) 1 in out between –1 and 1