The while Loop Syntax while condition statements As

  • Slides: 81
Download presentation
The while Loop Syntax while (condition) { statements } • As long condition is

The while Loop Syntax while (condition) { statements } • As long condition is true, the statements in the while loop execute.

The while Loop • The code: while (balance < target. Balance) { year++; double

The while Loop • The code: while (balance < target. Balance) { year++; double interest = balance * RATE / 100; balance = balance + interest; }

Syntax 6. 1 while Statement

Syntax 6. 1 while Statement

The while Loop • For a variable declared inside a loop body: – Variable

The while Loop • For a variable declared inside a loop body: – Variable is created for each iteration of the loop – And removed after the end of each iteration while (balance < target. Balance) { year++; double interest = balance * RATE / 100; balance = balance + interest; } // interest no longer declared here

Trace • balance = 10000 • rate = 5; • How many years until

Trace • balance = 10000 • rate = 5; • How many years until we reach target. Balance >= $20, 000?

Trace • target. Balance = 20000

Trace • target. Balance = 20000

1 /** 2 A class to monitor the growth of an investment that 3

1 /** 2 A class to monitor the growth of an investment that 3 accumulates interest at a fixed annual rate. 4 */ 5 public class Investment 6 { 7 private double balance; 8 private double rate; 9 private int year; 10 11 /** 12 Constructs an Investment object from a starting balance and 13 interest rate. 14 @param a. Balance the starting balance 15 @param a. Rate the interest rate in percent 16 */ 17 public Investment(double a. Balance, double a. Rate) 18 { 19 balance = a. Balance; 20 rate = a. Rate; 21 year = 0; 22 } 23 Continued

24 25 26 27 28 29 30 31 32 33 34 35 36 37

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 /** Keeps accumulating interest until a target balance has been reached. @param target. Balance the desired balance */ public void wait. For. Balance(double target. Balance) { while (balance < target. Balance) { year++; double interest = balance * rate / 100; balance = balance + interest; } } /** Gets the current investment balance. @return the current balance */ public double get. Balance() { return balance; } Continued

48 49 50 51 52 53 54 55 56 57 } /** Gets the

48 49 50 51 52 53 54 55 56 57 } /** Gets the number of years this investment has accumulated interest. @return the number of years since the start of the investment */ public int get. Years() { return year; }

1 /** 2 This program computes how long it takes for an investment 3

1 /** 2 This program computes how long it takes for an investment 3 to double. 4 */ 5 public class Investment. Runner 6 { 7 public static void main(String[] args) 8 { 9 final double INITIAL_BALANCE = 10000; 10 final double RATE = 5; 11 Investment invest = new Investment(INITIAL_BALANCE, RATE); 12 invest. wait. For. Balance(2 * INITIAL_BALANCE); 13 int years = invest. get. Years(); 14 System. out. println("The investment doubled after " 15 + years + " years"); 16 } 17 } Program Run: The investment doubled after 15 years

Common Error: Infinite Loops • Example: – forgetting to update the variable that controls

Common Error: Infinite Loops • Example: – forgetting to update the variable that controls the loop int years = 1; while (years <= 20) { double interest = balance * RATE / 100; balance = balance + interest; }

Common Error: Infinite Loops • Example: – incrementing instead of decrementing int years =

Common Error: Infinite Loops • Example: – incrementing instead of decrementing int years = 20; while (years > 0) { double interest = balance * RATE / 100; balance = balance + interest; years++; } • loop runs forever – must kill program

Common Error: Off-by-One Errors • Off-by-one error: a loop executes one too few, or

Common Error: Off-by-One Errors • Off-by-one error: a loop executes one too few, or one too many, times. int years = 0; while (balance < target. Balance) { years++; balance = balance * (1 + RATE / 100); } System. out. println("The investment doubled after " + year + " years. "); • Should years start at 0 or 1? • Should the test be < or <= ?

Avoiding Off-by-One Error • Look at a scenario with simple values: initial balance: $100

Avoiding Off-by-One Error • Look at a scenario with simple values: initial balance: $100 interest rate: 50% • after year 1, the balance is $150 after year 2 it is $225, or over $200 • so the investment doubled after 2 years the loop executed two times, incrementing years each time Therefore: years must start at 0, not at 1.

Avoiding Off-by-One Error • interest rate: 100% • after one year: balance is 2

Avoiding Off-by-One Error • interest rate: 100% • after one year: balance is 2 * initial. Balance • loop should stop Therefore: must use < not <=

Problem Solving: Hand-Tracing • What value is displayed? int n = 1729; int sum

Problem Solving: Hand-Tracing • What value is displayed? int n = 1729; int sum = 0; while (n > 0) { int digit = n % 10; sum = sum + digit; n = n / 10; } System. out. println(sum);

Hand-Tracing - Step by Step • Step 1 • Step 2

Hand-Tracing - Step by Step • Step 1 • Step 2

Hand-Tracing - Step by Step • Step 3

Hand-Tracing - Step by Step • Step 3

Hand-Tracing - Step by Step • Step 4

Hand-Tracing - Step by Step • Step 4

Hand-Tracing - Step by Step • Step 5

Hand-Tracing - Step by Step • Step 5

Hand-Tracing - Step by Step • Step 6

Hand-Tracing - Step by Step • Step 6

Hand-Tracing - Step by Step • Step 7

Hand-Tracing - Step by Step • Step 7

Hand-Tracing - Step by Step • Step 8

Hand-Tracing - Step by Step • Step 8

Hand-Tracing - Step by Step • Step 9 • Step 10 The sum, which

Hand-Tracing - Step by Step • Step 9 • Step 10 The sum, which is 19, is printed

The for Loop • Could use a while loop controlled by a counter int

The for Loop • Could use a while loop controlled by a counter int counter = 1; // Initialize the counter while (counter <= 10) // Check the counter { System. out. println(counter); counter++; // Update the counter } • Instead use a special type of loop called for loop for (int counter = 1; counter <= 10; counter++) { System. out. println(counter); }

Syntax 6. 2 for Statement

Syntax 6. 2 for Statement

The for Loop • A for loop can count down instead of up: for

The for Loop • A for loop can count down instead of up: for (int c = 10; c >= 0; c--) • The increment or decrement need not be in steps of 1: for (int c = 0; c <= 10; c = c + 2)

The for Loop • If the counter variable is defined in the loop header,

The for Loop • If the counter variable is defined in the loop header, – It does not exist after the loop for (int counter = 1; counter <= 10; counter++) {. . . } // counter no longer declared here

The for Loop • If you declare the counter variable before the loop, –

The for Loop • If you declare the counter variable before the loop, – You can continue to use it after the loop int counter; for (counter = 1; counter <= 10; counter++) {. . . } // counter still declared here

The for Loop • To traverse all the characters of a string: for (int

The for Loop • To traverse all the characters of a string: for (int i = 0; i < str. length(); i++) { char ch = str. char. At(i); Process ch. } • The counter variable i starts at 0, and the loop is terminated when i reaches the length of the string.

The for Loop • To compute the growth of our savings account over a

The for Loop • To compute the growth of our savings account over a period of years, – Use a for loop because the variable year starts at 1 and then moves in constant increments until it reaches the target for (int year = 1; year <= number. Of. Years; year++) { Update balance. }

The for Loop Flowchart for (int year = 1; year <= number. Of. Years;

The for Loop Flowchart for (int year = 1; year <= number. Of. Years; year++) { Update balance. }

1 /** 2 A class to monitor the growth of an investment that 3

1 /** 2 A class to monitor the growth of an investment that 3 accumulates interest at a fixed annual rate 4 */ 5 public class Investment 6 { 7 private double balance; 8 private double rate; 9 private int year; 10 11 /** 12 Constructs an Investment object from a starting balance and 13 interest rate. 14 @param a. Balance the starting balance 15 @param a. Rate the interest rate in percent 16 */ 17 public Investment(double a. Balance, double a. Rate) 18 { 19 balance = a. Balance; 20 rate = a. Rate; 21 year = 0; 22 } 23 Continued

24 25 26 27 28 29 30 31 32 33 34 35 36 37

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 /** Keeps accumulating interest until a target balance has been reached. @param target. Balance the desired balance */ public void wait. For. Balance(double target. Balance) { while (balance < target. Balance) { year++; double interest = balance * rate / 100; balance = balance + interest; } } Continued

39 40 41 42 43 44 45 46 47 48 49 50 51 52

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 /** Keeps accumulating interest for a given number of years. @param number. Of. Years the number of years to wait */ public void wait. Years(int number. Of. Years) { for (int i = 1; i <= number. Of. Years; i++) { double interest = balance * rate / 100; balance = balance + interest; } year = year + n; } /** Gets the current investment balance. @return the current balance */ public double get. Balance() { return balance; } Continued

62 63 64 65 66 67 68 69 70 71 } /** Gets the

62 63 64 65 66 67 68 69 70 71 } /** Gets the number of years this investment has accumulated interest. @return the number of years since the start of the investment */ public int get. Years() { return year; }

1 /** 2 This program computes how much an investment grows in 3 a

1 /** 2 This program computes how much an investment grows in 3 a given number of years. 4 */ 5 public class Investment. Runner 6 { 7 public static void main(String[] args) 8 { 9 final double INITIAL_BALANCE = 10000; 10 final double RATE = 5; 11 final int YEARS = 20; 12 Investment invest = new Investment(INITIAL_BALANCE, RATE); 13 invest. wait. Years(YEARS); 14 double balance = invest. get. Balance(); 15 System. out. printf("The balance after %d years is %. 2 fn", 16 YEARS, balance); 17 } 18 } Program Run The balance after 20 years is 26532. 98

The do Loop • Executes the body of a loop at least once and

The do Loop • Executes the body of a loop at least once and performs the loop test after the body is executed. • Use for input validation int value; do { System. out. print("Enter an integer < 100: "); value = in. next. Int(); } while (value >= 100);

The do Loop int value; do { System. out. print( "Enter an integer <

The do Loop int value; do { System. out. print( "Enter an integer < 100: "); value = in. next. Int(); } while (value >= 100);

Sentinel Values • In the military, a sentinel guards a border or passage. In

Sentinel Values • In the military, a sentinel guards a border or passage. In computer science, a sentinel value denotes the end of an input sequence or the border between input sequences.

Sentinel Values • A sentinel value denotes the end of a data set, but

Sentinel Values • A sentinel value denotes the end of a data set, but it is not part of the data. • Often times 0 is used as a sentinel value – keep accepting input until a 0 is typed • If 0 is valid data, -1 is a common sentinel value

Application using Sentinel Values • To compute the average of a set of salaries

Application using Sentinel Values • To compute the average of a set of salaries – use -1 to indicate termination • Inside the loop – Read the input – process it if the input is not -1

1 import java. util. Scanner; 2 3 /** 4 This program prints the average

1 import java. util. Scanner; 2 3 /** 4 This program prints the average of salary values that are terminated with a sentinel. 5 */ 6 public class Sentinel. Demo 7 { 8 public static void main(String[] args) 9 { 10 double sum = 0; 11 int count = 0; 12 double salary = 0; 13 System. out. print("Enter salaries, -1 to finish: "); 14 Scanner in = new Scanner(System. in); 15 16 // Process data until the sentinel is entered 17 Continued

16 17 18 19 20 21 22 23 24 25 26 27 28 29

16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 } 40 } // Process data until the sentinel is entered while (salary != -1) { salary = in. next. Double(); if (salary != -1) { sum = sum + salary; count++; } } // Compute and print the average if (count > 0) { double average = sum / count; System. out. println("Average salary: " + average); } else { System. out. println("No data"); } Continued

Boolean Sentinel Values System. out. print("Enter salaries, -1 to finish: "); boolean done =

Boolean Sentinel Values System. out. print("Enter salaries, -1 to finish: "); boolean done = false; while (!done) { value = in. next. Double(); if (value == -1) { done = true; } else { Process value } }

has. Next • What happens if 0 and -1 are valid input? – in.

has. Next • What happens if 0 and -1 are valid input? – in. has. Next. Double() returns false if the input is not a double – By the way, 1 can be read as double, but 1. 0 cannot be read as an int System. out. print("Enter values, Q to quit: "); while (in. has. Next. Double()) { value = in. next. Double(); Process value. }

The “Loop and a Half” Problem Sometimes a loop has to be terminated in

The “Loop and a Half” Problem Sometimes a loop has to be terminated in the middle. Here are two different approaches: • Use a Boolean variable • Combine an assignment and a test in the loop condition boolean done = false; while (!done) { String input = in. next(); if (input. equals("Q")) { done = true; } else { Process data. } } while (!(input = in. next()). equals("Q")) { Process data. }

Common Loop Algorithm: Sum • Sum - keep a running total: a variable to

Common Loop Algorithm: Sum • Sum - keep a running total: a variable to which you add each input value: double total = 0; while (in. has. Next. Double()) { double input = in. next. Double(); total = total + input; }

Common Loop Algorithm: Average • Average - count how many values you have: double

Common Loop Algorithm: Average • Average - count how many values you have: double total = 0; int count = 0; while (in. has. Next. Double()) { double input = in. next. Double(); total = total + input; count++; } double average = 0; if (count > 0) { average = total / count; }

Common Loop Algorithm: Counting Matches • Count how many spaces are in a string:

Common Loop Algorithm: Counting Matches • Count how many spaces are in a string: int spaces = 0; for (int i = 0; i < str. length(); i++) { char ch = str. char. At(i); if (ch == ' ’) { spaces++; } }

Common Loop Algorithm: Counting Matches • Count how many words in the input have

Common Loop Algorithm: Counting Matches • Count how many words in the input have at most three letters: int short. Words = 0; while (in. has. Next()) { String input = in. next(); if (input. length() <= 3) { short. Words++; } }

Common Loop Algorithm: Maximum • To find the largest value, update the largest value

Common Loop Algorithm: Maximum • To find the largest value, update the largest value seen so far whenever you see a larger one. double largest = in. next. Double(); while (in. has. Next. Double()) { double input = in. next. Double(); if (input > largest) { largest = input; } }

Common Loop Algorithm: Minimum • To find the smallest value, reverse the comparison. double

Common Loop Algorithm: Minimum • To find the smallest value, reverse the comparison. double smallest = in. next. Double(); while (in. has. Next. Double()) { double input = in. next. Double(); if (input < smallest) { smallest = input; } }

Common Loop Algorithm: Comparing Adjacent Values • Check whether a sequence of inputs contains

Common Loop Algorithm: Comparing Adjacent Values • Check whether a sequence of inputs contains adjacent duplicates such as 1 7 2 9 9 4 9: double input = 0; while (in. has. Next. Double()) { double previous = input; input = in. next. Double(); if (input == previous) { System. out. println("Duplicate input"); } }

Exam 2 Question 1 • Write a loop that prompts the user for a

Exam 2 Question 1 • Write a loop that prompts the user for a number (a double) and prints the number. If the user types a negative number, the loop will stop and the program will print “quit”

Exam 2 Question 2 • Modify your program so that it also quits if

Exam 2 Question 2 • Modify your program so that it also quits if the user types characters, i. e. , something that is not a number.

Exam 2 Question 3 • Modify your program so that it does not use

Exam 2 Question 3 • Modify your program so that it does not use an if statement.

Exam 2 Question 4 • Modify your program so that when it quits it

Exam 2 Question 4 • Modify your program so that when it quits it prints the sum of the number you typed.

Exam 2 Question 5 • Modify your program so that when it quits it

Exam 2 Question 5 • Modify your program so that when it quits it prints the largest number you typed.

Exam 2 Question 6 • Write a program that prompts the user to enter

Exam 2 Question 6 • Write a program that prompts the user to enter a string and then prints each character on a separate line.

Exam 2 Question 7 • Modify your program so that it prints “z” found”

Exam 2 Question 7 • Modify your program so that it prints “z” found” if the string contains the letter z.

Exam 2 Question 8 • Modify your program search for one instance of the

Exam 2 Question 8 • Modify your program search for one instance of the letter z so that it prints “z” found” or “z NOT found” once at the end.

Nested Loops • One loop inside another loop. • Print a table of the

Nested Loops • One loop inside another loop. • Print a table of the powers of x, like this: • Pseudocode Print table header. For x from 1 to 10 Print table row. Print new line.

Nested Loops • To print the values for each exponent requires a second loop

Nested Loops • To print the values for each exponent requires a second loop For n from 1 to 4 Print xn. • The hour and minute displays in a digital clock are an example of nested loops. – The hours loop 12 times, and for each hour, the minutes loop 60 times.

Nested Loops • Let us see how this can be coded to produce:

Nested Loops • Let us see how this can be coded to produce:

Exam 2 Question 9 • Write a program to print a multiplication table from

Exam 2 Question 9 • Write a program to print a multiplication table from 1 to 12.

Exam 2 Question 10 What do the following nested loops display? for (int i

Exam 2 Question 10 What do the following nested loops display? for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { System. out. print(i + j); } System. out. println(); }

Exam 2 Question 10 What do the following nested loops display? for (int i

Exam 2 Question 10 What do the following nested loops display? for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { System. out. print(i + j); } System. out. println(); } Answer: 0123 1234 2345

Nested Loop Examples

Nested Loop Examples

Exam 2 Question 11 Write a program that asks the user to type a

Exam 2 Question 11 Write a program that asks the user to type a string and returns “duplicate character found” if the string contains two or more of the same characters.

7. 1 Arrays • An array is a list of values stored together. •

7. 1 Arrays • An array is a list of values stored together. • Array positions are numeric starting at zero. • Strings are special arrays of characters: s. char. At(0) • In Java you can create numeric arrays: double[] values = { 32, 54, 67. 5, 29};

Arrays • To access a value in an array, specify which “slot” you want

Arrays • To access a value in an array, specify which “slot” you want to use – use the [] operator values[4] = 35; • The “slot number” is called an index. • Each slot contains an element.

Arrays • Individual elements are accessed by an integer index i, using the notation

Arrays • Individual elements are accessed by an integer index i, using the notation array[i]. • An array element can be used like any variable. System. out. println(values[4]);

Syntax 7. 1 Arrays

Syntax 7. 1 Arrays