350 likes | 358 Vues
Learn about while, for, and do...while loops in programming, including how to use them and when to choose each type. Examples and explanations provided.
E N D
Chapter 6 – Lots of Loops! September 28, 2010
Boolean expression Loop body
Three types of loops • A while loop, in which the loop-controlling Boolean expression is the first statement in the loop • A for loop, which is usually used as a concise format in which to execute loops • A do…while loop, in which the loop-controlling Boolean expression is the last statement in the loop
USING THE while LOOP • While(Boolean expression)…. • Boolean expression must involve a ‘loop control variable’ • Loop control variable must be incremented/decremented somewhere within the loop • Otherwise, the loop may be ‘infinite’ meaning incapable of being exited
Loop control variable • Can also be set by invoking a user to establish a value for it • Can be of almost any data type
Int val = 1; While(val<11) { System.out.println(val); val = val + 1; }
Infinite Loops While(4>2) System.out.println(“Hello”);
How many times does “Hello” get printed here?? loopCount = 1; While(loopCount<3) { System.out.println(“Hello”); loopCount = loopCount + 1; }
How many times does “Hello” get printed here?? loopCount = 1; While(loopCount<3) System.out.println(“Hello”); loopCount = loopCount + 1;
How many times does “Hello” get printed here?? loopCount = 1; While(loopCount<3); { System.out.println(“Hello”); loopCount = loopCount + 1; }
How many times does “Hello” get printed here?? loopCount = 3; While(loopCount>1) { System.out.println(“Hello”); loopCount = loopCount - 1; }
Using a while loop to control an indefinite loop • An indefinite loop is one that is controlled by user input—you don’t know how many times it will execute
import javax.swing.JOptionPane; public class BankBalance { public static void main(String[] args) { int selection; String balanceString; double balance; int tempBalance; int year = 1; final double INT_RATE = 0.03; balanceString = JOptionPane.showInputDialog(null, "Enter initial bank balance"); balance = Double.parseDouble(balanceString);
selection = JOptionPane.showConfirmDialog(null, "Do you want to see next year’s balance?"); while(selection == JOptionPane.YES_OPTION) { balance = balance + balance * INT_RATE; // Note: the next two statements round the balance tempBalance = (int)(balance * 100); balance = tempBalance / 100.0; selection = JOptionPane.showConfirmDialog(null, "After " + year + " years at " + INT_RATE + " interest rate, balance is $" + balance + "\nDo you want to see the balance at the end " + "\nof another year?"); year = year + 1; } System.exit(0); } }
while(selection == JOptionPane.YES_OPTION) • If the user selects any option other than Yes, the loop body never executes and the next statement to execute is the System.exit(0) • If the user selects Yes, all five statement in the loop body execute
When to use indefinite loops.. • Programmers use indefinite loops when validating data • Validating data is the process of ensuring that a value falls within a specified range
Import javax.swing.*; Public class EnterSmallValue { public static void main(string[] args) { int userEntry; String userString; userString = JOptionPane.showInputDialog(null,”Please enter an integer no higher than 3”); userEntry = Integer.parseInt(userString); while(userEntry > 3) { userString = JOptionPane.showInputDialog(null,”The number you entered was too high\n” + “Please enter an integer no higher than 3”); userEntry = Integer.parseInt(userString); } JOptionPane.showMessageDialog(null, “You entered “ + userEntry); Syste.exit(0); } }
Using shortcut Arithmetic Operators int value; value = 24; ++value; // Result – value is 25 value = 24; value++; // Result – value is 25 value = 24; value = value + 1; //Result – value is 25 Value = 24; Value += 1; // Result – value is 25
Prefix and postfix increment operators • These are unary operators, meaning that they operate on a single operand • Prefix: ++a; • Postfix: a++; • In prefix, the variable is incremented and then used • In postfix, the variable is used and then incremented
Examples of prefix and postfix int a = 1, b; b = ++a; Here, both b and a end up with the value 2 stored within them Int c = 1, d; d = ++c; Here, d winds up as 1 and c as 2
Using a for Loop • The for loop is used when a definite number of loop iterations is required • Following the for is an opening ( followed by three sections separated by semicolons and then a closing )
Three sections in parentheses Initializing the loop control variable Testing the loop control variable This must be a Boolean Expression If the Boolean Expression is true, the body of the loop is entered and executed if the Boolean Expression evaluates to false, control passes to the first executable statement following the loop body Updating the loop control variable
For(int val = 1; val < 11; ++val) System.out.println(val); • Does the same thing as….. int val = 1; while(val<11) { System.out.println(val); val = val + 1; }
Permissible For() statements—all of these are for(g=0,h=1;g<6;++g) for(g=0;g<3&&h>1;++g) for(g=5;g>=1;--g) for(;x<10;++x)
for loops • The test is applied at the beginning of the loop
THE do…while LOOP The test is applied at the end of the loop Checks the value of the loop control variable at the bottom of the loop after one repetition has occurred—will always go through the body of the loop at least once
Loop body Test of loop control variable True False
You can nest loops for(customer = 1; customer <= 20; ++customer) for(label = 1; label <= 3; ++label) printlabelMethod(); Or…printlabelMethod(customer, label);
import javax.swing.JOptionPane; • public class BankBalanceVaryingInterest • { • public static void main(String[] args) • { • int selection; • String balanceString; • double balance; • int tempBalance; • int year = 1; • double interest; • balanceString = JOptionPane.showInputDialog(null, • "Enter initial bank balance"); • balance = Double.parseDouble(balanceString); • selection = JOptionPane.showConfirmDialog(null, • "Do you want to see next year’s balance?"); • while(selection == JOptionPane.YES_OPTION) • {
for(interest = 0.02; interest <= 0.05; interest += 0.01) { balance = balance + balance * interest; tempBalance = (int)(balance * 100); balance = tempBalance / 100.0; JOptionPane.showMessageDialog(null, "After " + year + " years at " + interest + " interest rate, balance is $" + balance); } selection = JOptionPane.showConfirmDialog(null, "Do you want to see the balance at the end " + "\nof another year?"); year = year + 1; } System.exit(0); } }
public class IncrementDemo { public static void main(String[] args) { int myNumber, answer; myNumber = 17; answer = ++myNumber; System.out.println ("When myNumber is initialized to 17 and answer = ++myNumber"); System.out.println(" myNumber is " + myNumber); System.out.println(" and answer is " + answer); myNumber = 17; answer = myNumber++; System.out.println ("When myNumber is initialized to 17 and answer = myNumber++"); System.out.println(" myNumber is " + myNumber); System.out.println(" and answer is " + answer); } • }