Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or...
Transcript of Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or...
![Page 1: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/1.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
COMP-202
Programming withIteration
![Page 2: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/2.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Repetition Statements• Repetition statements or iteration statements allow
us to execute a statement multiple times repetitively• They are often simply referred to as loops• Like conditional statements, they are controlled by
boolean expressions• Java has three kinds of repetition statements: the while loop, the do loop, and the for loop
• The programmer must choose the right kind of loop for the situation
2
![Page 3: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/3.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
COMP-202
The while Statement
![Page 4: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/4.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
The while Statement (1)• The while statement has the following syntax:
4
while (condition) statement;
The condition must be a boolean expression. If it is true, the statement is executed and the
condition is evaluated againwhile is a Javareserved word
The statement is executed repetitively until
the condition becomes false
![Page 5: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/5.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Logic of a while Loop
5
condition?
statement
true
false
![Page 6: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/6.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
The while Statement (2)• Note that if the condition of a while statement is
false initially, the statement is never executed• Therefore, the body of a while loop will execute
zero or more times
6
![Page 7: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/7.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Counter.javapublic class Counter {
! public static void main(String[] args) {
final int LIMIT = 5; int count = 1;
while (count <= LIMIT) { System.out.println (count); count = count + 1; }
System.out.println ("Done."); }}
7
What does this print out?
![Page 8: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/8.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
BusPercentage.javafinal int NUM_SEATS = 56;int passengers; double ratio;Scanner scan = new Scanner(System.in);System.out.print ("Enter the number of passengers “ + “(0 to “ + NUM_SEATS + "): ");passengers = scan.nextInt();while (passengers < 0 || passengers > NUM_SEATS){ if (passengers > NUM_SEATS) System.out.print("Too many... Try again: "); else System.out.print(“Impossible! Try again: "); passengers = scan.nextInt();}ratio = (double)passengers / NUM_SEATS;DecimalFormat fmt = new DecimalFormat(“0.##”);System.out.println ("The bus is " + fmt.format(ratio*100) + ”% full.");
8
![Page 9: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/9.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Infinite Loops• The body of a while loop must eventually make
the condition false• If not, it is an infinite loop, which will execute
until the user interrupts the program• This is a common type of logical error• You should always double check to ensure that
your loops terminate eventually
9
![Page 10: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/10.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Abyss.javapublic class Abyss { public static void main (String[] args) { int count = 1; System.out.println("I'm going in...");
while (count <= Integer.MAX_VALUE) { System.out.println (count); count = count - 1; } System.out.println("Found the bottom” + “ of the abyss!"); }}
10
What is wrong here?Which statement is never reached?
![Page 11: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/11.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Nested Loops• Similar to nested if statements, loops can be
nested as well• That is, the body of a loop could contain another
loop• Each time through the outer loop, the inner loop
will go through its entire set of iterations
11
![Page 12: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/12.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
PalindromeTester.javaString str, another = "y"; int left, right;Scanner scan = new Scanner (System.in);
while (another.equalsIgnoreCase("y")) { // allows y or Y System.out.println ("Enter a potential palindrome:"); str = scan.nextLine(); left = 0; right = str.length() - 1; while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; } if (left < right) System.out.println ("That string is NOT a palindrome."); else System.out.println ("That string IS a palindrome."); System.out.print ("Test another palindrome (y/n)? "); another = scan.nextLine();}
12
![Page 13: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/13.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
COMP-202
The do Statement
![Page 14: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/14.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
The do Statement• The do statement has the following syntax:
14
do { statement;} while (condition);
do is a Javareserved word
The statement is executed repetitively until
the condition becomes false
Do loops execute statement at least once!
![Page 15: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/15.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Logic of a do Loop
15
statement
false
truecondition?
![Page 16: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/16.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Comparing while and do Loops
16
statement
false
truecondition?
condition?
statement
true
false
While loop: Do loop:
![Page 17: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/17.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Counter2.javapublic class Counter2 {
! public static void main(String[] args) {
final int LIMIT = 5; int count = 0;
do { count = count + 1; System.out.println (count); } while (count < LIMIT); System.out.println ("Done."); }}
17
What does this print out?
![Page 18: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/18.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
ReverseNumber.javaimport java.util.Scanner;public class ReverseNumber {! public static void main (String[] args) { int number, lastDigit, reverse = 0; Scanner scan = new Scanner (System.in); System.out.print ("Enter a positive integer: "); number = scan.nextInt(); do { lastDigit = number % 10; reverse = (reverse * 10) + lastDigit; number = number / 10; } while (number > 0); System.out.println ("That number reversed is " + reverse); }}
18
How does this program work?
![Page 19: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/19.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
COMP-202
The for Statement
![Page 20: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/20.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
The for Statement• The for statement has the following syntax:
20
for (initialization; condition; increment) statement;
for is a Javareserved word
The statement is executed until the condition becomes false
The increment part is executed at the end of each iteration
![Page 21: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/21.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
for - while Equivalence• A for loop is equivalent to the following while
loop:
21
initialization;while (condition) { statement; increment;}
![Page 22: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/22.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Logic of a for Loop
22
condition?
statement
true
false
initialization
increment
![Page 23: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/23.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
More on the for Statement• Like for a while loop, the condition of a for
statement is tested prior to executing the loop body
• Therefore, the body of a for loop will execute zero or more times
• It is well suited for executing a statement a specific number of times that can be determined in advance
23
![Page 24: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/24.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Counter3.javapublic class Counter3 {
! public static void main(String[] args) {
final int LIMIT = 5; for (int count=1; count <= LIMIT; count++) System.out.println(count);
System.out.println("Done."); }}
24
What does this print out?
![Page 25: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/25.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Multiples.javafinal int PER_LINE = 5;int value, limit, mult, count = 0;Scanner scan = new Scanner(System.in);System.out.print ("Enter a positive value: ");value = scan.nextInt();System.out.print ("Enter an upper limit: ");limit = scan.nextInt();System.out.println("The multiples of " + value + " between " + value + " and " + limit + " (inclusive) are:");
for (mult = value; mult <= limit; mult += value) { System.out.print (mult + "\t"); count++; if (count % PER_LINE == 0) System.out.println();}
25
What is this program doing?
![Page 26: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/26.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Stars.javapublic class Stars {
! public static void main (String[] args) {
final int MAX_ROWS = 10;
for (int row = 1; row <= MAX_ROWS; row++) { for (int star = 1; star <= row; star++) System.out.print("*"); System.out.println(); } }}
26
What shape does this program print?
![Page 27: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/27.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
X.javafinal int MAX_ROWS = 10;
for (int row = 1; row <= MAX_ROWS; row++) { for (int space = 1; space <= MAX_ROWS-row; space++) System.out.print(" "); ! for (int star = 1; star <= row*2; star++) System.out.print("*"); System.out.println();}for (int trunc=3; trunc>0; trunc--){ for (int space = 1; space <= MAX_ROWS-1; space++) System.out.print(" "); System.out.println("**");}
27
What shape does this program print?
![Page 28: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/28.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
More on the for Loop• Each expression in the header of a for loop is
optional• If the initialization is left out, no initialization is
performed• If the condition is left out, it is always considered to be
true, and therefore creates an infinite loop• If the increment is left out, no increment operation is
performed• Both semi-colons are always required in the for
loop header
28
![Page 29: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/29.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
COMP-202
Thinking like a Programmer
![Page 30: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/30.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Top-Down Program Development• This refers to a way of thinking when you try to solve a
programming problem:• First, read and understand the problem• Then, subdivide the problem into chunks. Each chunk is one task,
like: initializing variables, inputs, outputs, if-statements and loops.• Then order all these elements in the correct order.• Lastly, only now start writing your code
• Steps 1-3 are either done in your head or on scrap paper. They are not done using the language editor or compiler. They do not need to be in Java even, they could be in simple English/French/etc.
30
![Page 31: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/31.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Sample Problem• Write a program that asks the user for a positive integer
number (including zero). The program then displays a solid square followed by a hollow square. The program does nothing if the user inputs a negative value.
31
**** ******** * ***** * ***** ****
n = 4
![Page 32: Programming with Iterationcs202/2013-01/web/lectures/jorg/05-loops.pdf• Repetition statements or iteration statements allow us to execute a statement multiple times repetitively](https://reader033.fdocuments.net/reader033/viewer/2022042909/5f3db8efe7829e5afe29f2cf/html5/thumbnails/32.jpg)
COMP-202 - Iterative Programming, © 2013 Jörg Kienzle and others
Split the Problem• Get the input and check for correctness• A general solution for n ≥ 3 is clearly possible:• How are the first and last line printed?• How do you space solid from hollow text?• How is a solid part of a square printed?• How is a hollow part of a square printed?• Print top, solid and hollow parts, and bottom
• What about n = 0, 1, 2 ?• Think of how your program will react
32