110 likes | 206 Views
Agenda. Classes vs Objects Role play Loop structures while loop do-while loop for loop. Class Acrobat. An acrobat can do 3 things: 1) Clap his or hands a given number of times. 2) Perform knee bends a given number of times. 3) Report how many exercises have been completed.
E N D
Agenda Classes vs Objects Role play Loop structures while loop do-while loop for loop
Class Acrobat An acrobat can do 3 things: 1) Clap his or hands a given number of times. 2) Perform knee bends a given number of times. 3) Report how many exercises have been completed.
Illegal instructions • Acrobat, clap 4 => only Acrobat objects can clap • Andrew, clap => clapping requires a number • Clap 3 => no object specified
while Loop • while loop executes a set of statements over and over again based on a condition. • takes the form: while (<condition>) { <statements> } • Example : Intnum=0; while (num < 5) { num += 1; } • Each execution of the loop is called an iteration.
do-while Loop • Similar to while loop, but the condition is not evaluated until after the first execution of the loop. Therefore, the do-while executes at least once. The form: do { <statements> } while (<condition>); • Example: do { System.out.print("Enter a number less than 4:"); playerNum = input.nextInt(); } while (playerNum >= 4);
for Loop • for Loop executes a set of statements a fixed number of times. The for statement takes the form: for (<initialization>; <condition>; <increment>) { <statements> } • example for (int i = 1; i <= 10; i++) { System.out.println(i); } How can this example change to equivalent while or do-while loop?
Infinite Loop • The condition of a loop is used to determine when the loop should stop executing. What happens, though, if the condition never becomes false? intnum = -1; while (num < 0) { num = -1; }
Infinite loop • One example is syntax error- semicolon after the condition; another example of a syntax error that can lead to an infinite loop is omitting the curly braces. while (num < 0); { //do nothing num += 1; } while (num < 0) System.out.println(“Enter a value”); num = input.nextInt();
Infinite loop • A logic error can also lead to an infinite loop condition. intnum = 1; do { num+= 1; } while (num >= 0); • In this case, the loop isn’t infinite because num is eventually assigned a number so large that an overflow results. An overflow occurs when there are not enough bits to store a number.
practice • an application that calculates the average of a set of numbers must sum the numbers and then divide the total by the count. • A run of the application looks simliar to: Enter a value( 0 to quit): 25 Enter a value( 0 to quit): 14 Enter a value( 0 to quit): 9 Enter a value( 0 to quit): 120 Average: 42.0
pseudocode Prompt user for a value while (value != 0) count value add value to sum of values prompt user for another value Display average of values (sum/count)