CS303E Loops 1 CS 303E Lecture 8: Loops lf-referentially, short for GNU's not UNIX, Unix-compatible software system developed the Free Software Foundation (FSF). Which uld be expanded to GNU’s not UNIX’s not UNIX, ich could be expanded to NU's not UNIX’s not UNIX’s not UNIX, which uld be expanded to…….
43
Embed
CS303ELoops1 CS 303E Lecture 8: Loops Self-referentially, short for GNU's not UNIX, a Unix-compatible software system developed by the Free Software Foundation.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
CS303E Loops 1
CS 303E Lecture 8:
LoopsSelf-referentially, short for GNU's not UNIX, a Unix-compatible software system developed by the Free Software Foundation (FSF). Which could be expanded to GNU’s not UNIX’s not UNIX,which could be expanded to GNU's not UNIX’s not UNIX’s not UNIX, whichcould be expanded to…….
CS303E Loops 2
Iteration – a Basic OperationExample of iteration – building a fence:
Move tools and materials to starting point.
Install first fence post.
Repeat until finished:
Move to position of next fence post.
Install next fence post.
Install fencing between new post
and previous post.
LoopBody ofloop isrepeated.
Initialization
Terminationcondition
CS303E Loops 3
while Loop — Syntax
while ( boolean_expression )statement;
or
while ( boolean_expression ){ statement;
. . .}
Continuationcondition
Loop body
CS303E Loops 4
Syntax and Semantics ofwhile Statements
while (<Boolean expression>) <statement>
while (<Boolean expression>){ <statement 1> . <statement n>}
?
statement
true
false
CS303E Loops 5
while Loop for Building Fence
Move tools and materials to starting point.
Install first fence post.
while (not finished)
{ Move to position of next fence post;
Install next fence post;
Install fencing between new post
and previous post;
}
Continuationcondition
CS303E Loops 6
Loops — two basic patternsCount-controlled loop: Number of iterations is determined before
the loop starts. Counts each iteration in a counter variable. Stops when the desired number of iterations
has been performed.
Event-controlled loop: Before each iteration, checks to see whether
some event has occurred. Continues until that event occurs. Number of iterations not known beforehand.
In general, avoid using != in loop termination conditions.
CS303E Loops 16
Event-controlled loop patterninitialization;while ( event has not occurred ){ do work; }Work must eventually cause event to occur.
HelloWorld in an Event Driven Programming World
while(true){System.out.print(“Hello World!! “);
}
CS303E Loops 17
Example – Sum powers of 2
Specification: Sum the powers of 2 up to a power <= limit.
Algorithm in pseudo-code:
1. Get value for limit;
2. Set sum to 0, power to 2;
3. While ( power <= limit )
{ a. Increment sum by power; // 2 + 4 + 8 + . . .
b. Multiply power by 2; // 4, 8, 16, . . .
}
4. Display sum;
CS303E Loops 18
Code – Sum powers of 2
limit = inputField.getNumber();
sum = 0;
power = 2;
while ( power <= limit )
{ sum = sum + power; // 2 + 4 + 8 + . . .
power = power * 2; // 4, 8, 16, . . .
}
outputField.setNumber (sum);
CS303E Loops 19
Mixing the two types of loops
Specification: Sum the first powers of 2, so long as power <= limit but not more than 10 powers.
max = maxField.getNumber();
limit = limitField.getNumber();
sum = 0; power = 2; count = 1;
while ( power <= limit && count <= max )
{ sum = sum + power; // 2 + 4 + 8 + . . .
power = power * 2; // 4, 8, 16, . . .
count = count + 1; // 2, 3, 4, . . .
}
outputField.setNumber (sum);
CS303E Loops 20
CS 303E Lecture 9:Loops II
"An apprentice carpenter may want only a hammer and saw, but a master craftsman employs many precision tools. Computer programming likewise requires sophisticated tools to cope with the complexity of real applications,and only practice with these tools will build skill in their use."- Robert L. Kruse, Data Structures and Program Design
CS303E Loops 21
Prime Numbers
Write a program to determine if a given number is prime.
Analysis / Design (algorithm)
CS303E Loops 22
Prime Number Implementation
CS303E Loops 23
Other Loops
Java provides syntax for two other types of loops
do - while loop for loop Any of these could be rewritten as a while loop.
CS303E Loops 24
do-while Loop Syntax
do
{ //body of loop
First_Statement;
...
Last_Statement;
} while(Boolean_Expression); Initialization code may precede loop body
CS303E Loops 25
do-while Loop
Loop test is after loop body so the body must execute at least once (minimum of at least one iteration)
May be either count controlled or event controlled loop• Good choice for event controlled loop
Something in body of loop should eventually cause Boolean_Expression to be false
CS303E Loops 26
do-while Exampleint count = 1;int number = 10;do //Display integers 1 - 10 on one line
while (counter <= 20){ sum = sum + counter; output.append(Format.justify('r', counter, 5) + Format.justify('r', sum, 10) + "\n"); counter++;}
while (counter <= 20){ sum = sum + counter; output.append(counter + " " + sum + "\n"); counter++;}
CS303E Loops 42
Justification of Text Output
CS303E Loops 43
Some practical considerationswhen using loops
The most common loop errors are unintended infinite loops and off-by-one errors in counting loops
Sooner or later everyone writes an unintentional infinite loop• To get out of an unintended infinite loop enter ^C (control-C)
Loops should tested thoroughly, especially at the boundaries of the loop test, to check for off-by-one and other possible errors• "Tracing" a variable (outputting its value each time through the
loop) is a common technique to test loop counters and troubleshoot off-by-one and other loop errors