Presentation is loading. Please wait.

Presentation is loading. Please wait.

Loops, Part II IT108 George Mason University. Indefinite Loop Don’t always have access to the number of iterations ahead of time If a condition (user-response,

Similar presentations


Presentation on theme: "Loops, Part II IT108 George Mason University. Indefinite Loop Don’t always have access to the number of iterations ahead of time If a condition (user-response,"— Presentation transcript:

1 Loops, Part II IT108 George Mason University

2 Indefinite Loop Don’t always have access to the number of iterations ahead of time If a condition (user-response, limit reached, …) controls the number of iterations – indefinite loop is appropriate

3 While Loop

4 Using the while Loop while Loop- To execute a body of statements continually as long as the Boolean expression continues to be true Consists of the keyword while followed by a Boolean expression within parentheses followed by the body of the loop Use when you need to perform a task a predetermined number of times

5 while Loop while (loop-continuation-condition) { // loop-body; Statement(s); } int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; }

6 Trace while Loop int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Initialize count 0 0 int count MEMORY CONSOLE

7 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } (count < 2) is true 0 0 int count MEMORY CONSOLE

8 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Print Welcome to Java 0 0 int count MEMORY CONSOLE Welcome to Java!

9 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Increase count by 1 count is 1 now 0 0 int count MEMORY CONSOLE Welcome to Java! 1 1

10 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } (count < 2) is still true since count is 1 int count MEMORY CONSOLE Welcome to Java! 1 1

11 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Print Welcome to Java int count MEMORY CONSOLE Welcome to Java! 1 1

12 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Increase count by 1 count is 2 now int count MEMORY CONSOLE 1 1 Welcome to Java! 2 2

13 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } (count < 2) is false since count is 2 now int count MEMORY CONSOLE Welcome to Java! 2 2

14 Trace while Loop int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } The loop exits. Execute the next statement after the loop. int count MEMORY CONSOLE Welcome to Java! 2 2

15 Example: Sum of integers Write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input. INPUT: each of the integers OUTPUT: sum of integers PROCESS: 1.sum=0 2.INPUT number 3.While (number!=0) a)sum=sum + number b)INPUT number 4.DISPLAY sum

16 Flowchart: Sum of integers INPUT: each of the integers OUTPUT: sum of integers PROCESS: 1.sum=0 2.INPUT number 3.While (number!=0) a)sum=sum + number b)INPUT number 4.DISPLAY sum Number!=0 true false Start sum=0 INPUT number sum=sum+number DISPLAY sum Stop INPUT number

17 Program: Sum of integers package chapter04b; import javax.swing.JOptionPane; /** * This program reads and calculates the sum of an unspecified number of integers. * The input 0 signifies the end of the input. * @author Mihai Boicu */ public class IntegersSum { /** * This program reads and calculates the sum of an unspecified number of integers. * The input 0 signifies the end of the input. * @param args command line arguments not used */ public static void main(String[] args) { //intialize sum of all integers int sum=0; //Read the first integer: String numberString = JOptionPane.showInputDialog("Enter the first number:"); int number = Integer.parseInt(numberString); //while not the end of numbers while (number!=0) { //Update the sum sum+=number; //sum = sum + number //read the next integer numberString = JOptionPane.showInputDialog("Enter the next number:"); number = Integer.parseInt(numberString); } //DISPLAY the sum JOptionPane.showMessageDialog(null, "The sum of the integers is: "+sum); } } INPUT: each of the integers OUTPUT: sum of integers PROCESS: 1.sum=0 2.INPUT number 3.While (number!=0) a)sum=sum + number b)INPUT number 4.DISPLAY sum INPUT: each of the integers OUTPUT: sum of integers PROCESS: 1.sum=0 2.INPUT number 3.While (number!=0) a)sum=sum + number b)INPUT number 4.DISPLAY sum

18 Execution: Sum of integers public static void main(String[] args) { //intialize sum of all integers int sum=0; //Read the first integer: String numberString = JOptionPane.showInputDialog("Enter the first number:"); int number = Integer.parseInt(numberString); //while not the end of numbers while (number!=0) { //Update the sum sum+=number; //sum = sum + number //read the next integer numberString = JOptionPane.showInputDialog("Enter the next number:"); number = Integer.parseInt(numberString); } //DISPLAY the sum JOptionPane.showMessageDialog(null, "The sum of the integers is: "+sum); } int sum MEMORY int number 10 0 0 int sum int number 15 10 int sum int number 0 0 25

19 Caution Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations, using them could result in imprecise counter values and inaccurate results. This example uses int value for data. If a floating-point type value is used for data, (data != 0) may be true even though data is 0. // data should be zero double data = Math.pow(Math.sqrt(2), 2) - 2; if (data == 0) System.out.println("data is zero"); else System.out.println("data is not zero");

20 Caution

21 do…while loop Checks at the bottom of the loop after one repetition has occurred Loop body executes at least one time The loop starts with the keyword do The body of the loop is contained within curly braces

22 do-while Loop do { // Loop body; Statement(s); } while (loop-continuation-condition);

23 Which Loop to Use? The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. For example, a while loop in (a) in the following figure can always be converted into the following for loop in (b): A for loop in (a) in the following figure can generally be converted into the following while loop in (b) except in certain special cases (see Review Question 3.19 for one of them):

24 Which Loop to Use? Interchangeable – BUT, only one is the right choice! Definite: for loop Indefinite and at least one iteration: do/while Indefinite and not necessarily at least one iteration: while

25 Common Logic Error Semicolon to terminate loops (for/while) prior to the body! for (int i=0; i<10; i++); System.out.println("i is " + i); --------------------------------------------------- int play = JOptionPane.showConfirmDialog(null, “Play Game?"); while (play == JOptionPane.YES_OPTION); // play Scrabble

26 Caution, cont. Similarly, the following loop is also wrong: int i=0; while (i < 10); { System.out.println("i is " + i); i++; } In the case of the do loop, the following semicolon is needed to end the loop. int i=0; do { System.out.println("i is " + i); i++; } while (i<10); Logic Error Correct

27 Use of break and continue Used to alter the intended flow of execution break; //end the control structure continue; //end current iteration

28 Break a FOR

29 Break a WHILE

30 Break a DO WHILE

31 Continue a FOR

32 Continue a WHILE

33

34 Continue a DO WHILE

35 Ending a Loop with a Sentinel Value Often the number of times a loop is executed is not predetermined. You may use an input value to signify the end of the loop. Such a value is known as a sentinel value. Write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input.

36 Program: Sum of integers package chapter04b; import javax.swing.JOptionPane; /** * This program reads and calculates the sum of an unspecified number of integers. * The input 0 signifies the end of the input. * @author Mihai Boicu */ public class IntegersSum { /** * This program reads and calculates the sum of an unspecified number of integers. * The input 0 signifies the end of the input. * @param args command line arguments not used */ public static void main(String[] args) { //intialize sum of all integers int sum=0; //Read the first integer: String numberString = JOptionPane.showInputDialog("Enter the first number:"); int number = Integer.parseInt(numberString); //while not the end of numbers while (number!=0) { //Update the sum sum+=number; //sum = sum + number //read the next integer numberString = JOptionPane.showInputDialog("Enter the next number:"); number = Integer.parseInt(numberString); } //DISPLAY the sum JOptionPane.showMessageDialog(null, "The sum of the integers is: "+sum); } INPUT: each of the integers OUTPUT: sum of integers PROCESS: 1.sum=0 2.INPUT number 3.While (number!=0) a)sum=sum + number b)INPUT number 4.DISPLAY sum INPUT: each of the integers OUTPUT: sum of integers PROCESS: 1.sum=0 2.INPUT number 3.While (number!=0) a)sum=sum + number b)INPUT number 4.DISPLAY sum

37 Caution Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations, using them could result in imprecise counter values and inaccurate results. This example uses int value for data. If a floating-point type value is used for data, (data != 0) may be true even though data is 0. // data should be zero double data = Math.pow(Math.sqrt(2), 2) - 2; if (data == 0) System.out.println("data is zero"); else System.out.println("data is not zero");

38 Caution

39 Example: House SF Calculate the total square footage of a house Allow the user to enter rooms and sizes Do not include bathrooms in the square footage INPUT: rooms: name, length, width OUTPUT: total SF and room SF PROCESS: Initialize the house SF, message while there are rooms –INPUT room name, length and width –Compute room SF –Update house SF –Update message with the current room DISPLAY: house SF, message

40 Design: House SF

41 Program: House SF public static void main(String[] args) { // room name used to exit the computation final String END_ROOM_NAME = "END"; // total house SF double houseSF = 0; // shown message with the answer String message = ""; // room name - used also as sentinel to exit the loop String roomName = ""; do { // INPUT room name roomName = JOptionPane.showInputDialog("Enter the name of the room (END to finish):"); // Check the sentinel if (!roomName.equalsIgnoreCase(END_ROOM_NAME)) { // INPUT width double width = Double.parseDouble(JOptionPane.showInputDialog("Width of " + roomName)); // INPUT length double length = Double.parseDouble(JOptionPane.showInputDialog("Length of " + roomName)); // COMPUTE SF double roomSF = width * length; // UPDATE house SF houseSF += roomSF; // UPDATE message message += roomName+" - "+roomSF+"SF ("+width+" x "+length+")\n"; } } while (!roomName.equalsIgnoreCase(END_ROOM_NAME)); // DISPLAY result JOptionPane.showMessageDialog(null, "HOUSE SF: "+houseSF+"\n"+message); } } Calculate the total square footage of a house Allow the user to enter rooms and sizes Do not include bathrooms in the square footage INPUT: rooms: name, length, width OUTPUT: total SF and room SF PROCESS: Initialize the house SF, message while there are rooms –INPUT room name, length and width –Compute room SF –Update house SF –Update message with the current room DISPLAY: house SF, message Calculate the total square footage of a house Allow the user to enter rooms and sizes Do not include bathrooms in the square footage INPUT: rooms: name, length, width OUTPUT: total SF and room SF PROCESS: Initialize the house SF, message while there are rooms –INPUT room name, length and width –Compute room SF –Update house SF –Update message with the current room DISPLAY: house SF, message

42 Using Loops Examples: Input Validation –Using while loop –Using do/while loop Repetition of activities –Make it work for ONE first!

43 Example: Salary Increase Write a program to process an employee’s salary increase. The raise will depend on a minimum of 2 years employed with the company and the rate of 5%. The program should prompt the user to enter the employee’s name, number of months employed and current salary. Note: Your implementation needs to be well-designed. This means, minimally: Verify all numeric input INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary

44 Example: Salary Increase Write a program to process an employee’s salary increase. The raise will depend on a minimum of 2 years employed with the company and the rate of 5%. The program should prompt the user to enter the employee’s name, number of months employed and current salary. Note: Your implementation needs to be well-designed. This means, minimally: Verify all numeric input INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary public class SalaryIncrease { /** * INPUT: name, months, salary * OUTPUT: increase, new salary * * @param args */ public static void main(String[] args) { // minimum employment final int MINIMUM_EMPL = 24; // raise rate final double RATE = 0.05;

45 public class SalaryIncrease { /** * INPUT: name, months, salary * OUTPUT: increase, new salary * * @param args */ public static void main(String[] args) { // minimum employment final int MINIMUM_EMPL = 24; // raise rate final double RATE = 0.05; //INPUT name String name; name = JOptionPane.showInputDialog("Enter the name of the employee:"); JOptionPane.showMessageDialog(null, "The employee name is:"+name); Example: Salary Increase INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary

46 //INPUT name String name; do { name = JOptionPane.showInputDialog("Enter the name of the employee:"); } while (name==""); JOptionPane.showMessageDialog(null, "The employee name is:"+name); Example: Salary Increase INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary NEVER USE == FOR STRINGS USE.EQUALS

47 //INPUT name String name; do { name = JOptionPane.showInputDialog("Enter the name of the employee:"); } while (name.equals("")); JOptionPane.showMessageDialog(null, "The employee name is:"+name); Example: Salary Increase INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary FOR STRINGS USE.EQUALS

48 // INPUT name String name; do { name = JOptionPane.showInputDialog("Enter the name of the employee:"); } while (name==null || name.equals("")); Example: Salary Increase INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary

49 // INPUT name String name; do { name = JOptionPane.showInputDialog("Enter the name of the employee:"); } while (name==null || name.equals("")); // INPUT months int months; do { months = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of months "+name+" was employed:")); } while (months < 0); Example: Salary Increase INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary

50 Example: Salary Increase Exception: Some command is not executing correctly. You can catch exceptions!

51 // INPUT months int months = -1; do { try { months = Integer.parseInt(JOptionPane.showInputDialog( "Enter the number of months "+name+" was employed:")); } catch (Exception e) { //ignore exceptions - errors } } while (months < 0); Example: Salary Increase INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary

52 int months = -1; do { try { months = Integer.parseInt(JOptionPane.showInputDialog( "Enter the number of months "+name+" was employed:")); } catch (Exception e) { //ignore exceptions - errors JOptionPane.showMessageDialog(null, "Invalid number format. Please use only digits."); } } while (months < 0); Example: Salary Increase INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary

53 // INPUT salary double salary = -1; do { try { salary = Double.parseDouble(JOptionPane.showInputDialog( "Enter the salary of " + name + ":")); } catch (Exception e) { // ignore exceptions - errors JOptionPane.showMessageDialog(null, "Invalid number format. Please use only digits."); } } while (salary < 0); // COMPUTE increase double increase = (months >= MINIMUM_EMPL) ? salary * RATE : 0; // COMPUTE new salary double newSalary = salary + increase; // DISPLAY increase, new salary JOptionPane.showMessageDialog(null, "The new salary for "+name+" is "+newSalary +"$.\nThe increase was "+increase+"$."); } Example: Salary Increase INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary INPUT: name, months, salary OUTPUT: increase, new salary PROCESS: 1.INPUT AND CHECK name, month, salary 2.COMPUTE increase, new salary 3.DISPLAY increase, new salary

54 Finding the Sales Amount Problem: You have just started a sales job in a department store. Your pay consists of a base salary and a commission. The base salary is $5,000. The scheme shown below is used to determine the commission rate. Sales AmountCommission Rate $0.01–$5,0008 percent $5,000.01–$10,00010 percent $10,000.01 and above12 percent Your goal is to earn $30,000 in a year. Write a program that will find out the minimum amount of sales you have to generate in order to make $30,000. INPUT: earning goal OUTPUT: sales

55 Finding the Sales Amount Problem: You have just started a sales job in a department store. Your pay consists of a base salary and a commission. The base salary is $5,000. The scheme shown below is used to determine the commission rate. Sales AmountCommission Rate $0.01–$5,0008 percent $5,000.01–$10,00010 percent $10,000.01 and above12 percent Your goal is to earn $30,000 in a year. Write a program that will find out the minimum amount of sales you have to generate in order to make $30,000. Commission needed = $30,000 - $5,000 = $25,000 Commission = Sales * Percent Sales = Commission / Percent Find the percent: Percent = 0.12 Sales = Commission / 0.12 = $25,000 / 0.12 = $208,333.33 Check the sales > $10,000

56 Example Allow the user to enter as many deposits into a bank account as they choose and calculate the average. Note: each deposit must be between $100 and $200. INPUT: all deposits OUTPUT: average PROCESS:


Download ppt "Loops, Part II IT108 George Mason University. Indefinite Loop Don’t always have access to the number of iterations ahead of time If a condition (user-response,"

Similar presentations


Ads by Google