240 likes | 426 Views
Iteration and Loop Statements. Horstmann Chapter 7. Loop statements control repeated execution of a block of statements. Each time the statements in the block are carried out, we speak of one iteration of the loop. Structure of a Loop.
E N D
Iteration and Loop Statements Horstmann Chapter 7 Loop statements control repeated execution of a block of statements Each time the statements in the block are carried out, we speak of one iteration of the loop
Structure of a Loop • Evaluate the continue-condition (a.k.a. the loop guard) • If the continue-condition is true, execute the loop body and go back to 1 • If the continue-condition is false, skip the loop body entirely and continue with the next line of code
false continue-condition? true loop-body statements next statement The WHILE loop while (i < 100) { System.out.print("."); i++; }
Printing 100 dots false i < 100? int i = 0; while (i < 100) { System.out.print("."); i++; } true print dot i++ next statement
Another example int count = 1; while (count != 100) { System.out.print(count + " "); count++; } Output: 1 2 3 4 5 6 7 8 9 10 11 12........97 98 99
Counting backwards int count = 100; while (count != 0) { System.out.print(count + " "); count--; } Output: 100 99 98 97 96 95..............3 2 1
Add up some integers • Set 'sum' to zero • Read in an integer (from JOptionPane; convert to int using Integer.parseInt() • While 'data' is not zero.. • Add 'data' to 'sum'; • Read in another integer into 'data' 4. Print out the value of 'sum'
Adding program int sum; int data; String dataString; dataString=JOptionPane.showInputDialog(null,”enter number:”); data = Integer.parseInt(dataString); while(data != 0) { dataString=JOptionPane.showInputMessage(null,”enter number:”); data = Integer.parseInt(dataString); sum = sum + data; //could have used: sum += data; } JOptionPane.showMessageDialog(null,”Numbers sum to ”+sum);
What is wrong with this loop? int count = 0; while (count != 99) { System.out.print(count + " "); count = count + 2; }
Calculating the Growth of an Investment • Invest $10,000, 5% interest, compounded annually
Growth of an investment • How many years will it take a bank account reached a particular balance? while (balance < targetBalance){ year++; double interest = balance * rate / 100; balance = balance + interest;}
Stand-alone growth program class GrowBalance { public static void main(String[] args){ double rate = 3.0; double balance = 500.0; double targetBalance = 1000.0 double year = 0; while (balance < targetBalance) { year++; double interest = balance * rate / 100; balance = balance + interest; System.out.println(“year ”+year+ “: balance ”+balance); } } }
Object-based investment growth public class Investment{ private double balance; private double rate; private int years; public Investment(double aBalance, double aRate) { balance = aBalance; rate = aRate; years = 0; } public void waitForBalance(double targetBalance) { while (balance < targetBalance){ years++; double interest = balance * rate / 100; balance = balance + interest; } } public int getYears() { return years; } public double getBalance(){ return balance; } }
Test program to create investment objects public class InvestmentTester { public static void main(String[] args) { final double INITIAL_BALANCE = 10000; final double RATE = 5; Investment invest = new Investment(INITIAL_BALANCE, RATE); invest.waitForBalance(2 * INITIAL_BALANCE); int years = invest.getYears(); System.out.println("The investment doubled after " + years + " years"); } }
Sequence processing Many tasks require the program to process a series of numbers. Question: how do we know when to stop? Answer 1: know in advance how long the sequence is... Answer 2: provide a sentinel value to signal the end...
Sample problems 1) Write a Java program that reads a sequence of positive integer values, terminated by a -1, and calculate their average. 2) Modify your program so that it reads in 5 and only 5 numbers and then calculates their average.
Developing a WHILE loop • Decide on a loop guard. The loop will terminate when this guard is false. • Set up initial conditions for loop. E.g. make sure variables in the guard are initialized. • Write the 'work' part of the loop body • Write the 'change' part of the loop body. This must potentially alter the value of the guard.
Things we know for certain • Before the loop: anything could be true • At the start of the loop body: the guard is guaranteed to be true • Immediately after the loop body: the guard is guaranteed to be false
Basic sequence operations Reduction. E.g. finding the average of a sequence Mapping: E.g. printing the square of each member of a sequence Filtering: E.g. doing something only with certain sequence elements
Doing it all at once Problem: Write a program which reads a sequence of positive integer values, terminated by -1, and prints the average of the square of the odd elements of the sequence. • Find the odd elements (filtering) • Compute their squares (mapping) • Calculate the average (reduction)