Upload
jesse-holmes
View
231
Download
3
Tags:
Embed Size (px)
Citation preview
Lecture 10
Flow of Control: Loops (Part 2)
COMP1681 / SE15
Introductionto Programming
SE15: Loops(2) 10–2
Today’s Learning Objectives
Meet do-while loops Learning about tracing and debugging code For you to learn more about techniques for planning the
solution to a programming problem For you to recognise the importance of writing clear,
readable, well-documented code
SE15: Loops(2) 10–3
Lecture Outline
do-while loops Top tips for loops Example of a nested loop Tracing code Debugging in Drjava Top tips for writing code
SE15: Loops(2) 10–4
do-while Loops
int count = 0;
do
{
System.out.print(count + “,”);count++;
} while (count <= 10);
!warning: the loop body is always executed once!
SE15: Loops(2) 10–5
Hints
Watch out for extra semicolons with for loopsfor (i=0; i < 10; i++);
Avoid declaring variables inside loops Avoid break statements if possible You cannot use do-while unless you are certain that
the loop can iterate at least once. If you have computation that changes some numeric
quantity by some equal amount each time, consider a for statement
A while statement is always the safest
SE15: Loops(2) 10–6
More torn up code
Reconstruct the following fragments of code to produce the following output:
0 4
0 3
1 4
1 3
3 4
3 3
public static void main (String [] args)
for ( int x = 0; x < 4; x++)
class MultipleFors
for ( int y = 4; y > 2; y--)
System.out.println(x + " " + y);if(x == 1)
x++;
Head First Java, Sierra & Bates, O’Reilly
SE15: Loops(2) 10–7
What does the following code do?class LoopTest{ public static void main(String [] args) { int y = 7; for(int x = 1; x < 8; x++) { y++; if(x > 4) System.out.print(++y + " "); if(y > 14) { System.out.println("x = " + x); break; } } }}
SE15: Loops(2) 10–8
UML Activity Diagrams(Flow diagrams)
for(int i = 0; i < 10; i++)
{
System.out.println(i);
}
System.out.println(“done”);
Is i < 10?
false
true
Declare int iSet i = 0
Enter loopbody
Print the value of i
Increment i
print “done”
Initial node
Final node
Action node
SE15: Loops(2) 10–9
Top tips for writing programs
Put the scaffolding in place, then stop, think and plan If the problem seems complex, simplify it or break it
down into more manageable pieces Write down in English the steps you need to take For each of the main steps of your solution, write a
comment in your main method Use the comments to remind you what to do at each
point in the program
SE15: Loops(2) 10–10
Simplifying the Problem
Convert only from °C to °F Perform a single conversion Steps become
1. Read temperature in °C from keyboard
2. Calculate temperature in °F
3. Output result of calculation to screen
SE15: Loops(2) 10–11
Commenting Your Code
// Temperature conversion program// Written by Nick Efford, 2005-10-18
public class Temperature {
public static void main(String[] args) { // Read temperature in Celsius
// Convert to Fahrenheit
// Output result of calculation }
}
SE15: Loops(2) 10–12
Top Tips
Adopt a good coding style Add a small amount of code at a time Compile and run after each new addition of code
Fix errors before adding more code! Use temporary println statements to test for correct
behaviour, or run in the debugger
SE15: Loops(2) 10–13
Writing Readable Programs
Use a good coding style Descriptive names for classes, methods, variables… Sensible use of blank lines and indentation Consistency!
Use an appropriate level of commenting Derive them from your pseudocode ‘Comment as you go’, don’t add them all at the end!
SE15: Loops(2) 10–14
Iteration 1(Pseudocode)
Read a temperature in Celsius from the keyboardConvert temperature from Celsius to FahrenheitOutput Fahrenheit temperature to screen
SE15: Loops(2) 10–15
Iteration 1(UML)
Read temperature inCelsius from keyboard
Convert temperaturefrom Celsius to Fahrenheit
Output Fahrenheittemperature to screen
Initial node
Final node
Action node
SE15: Loops(2) 10–16
Iteration 2(Pseudocode)
Read a temperature from the keyboardRead temperature scale from the keyboardIf temperature scale starts with ‘C’ or ‘c’: Convert temperature from Celsius to Fahrenheit Output Fahrenheit temperature to screenOtherwise if temperature scale starts with ‘F’ or ‘f’: Convert temperature from Fahrenheit to Celsius Output Celsius temperature to screenOtherwise: Print an error message on the screen
SE15: Loops(2) 10–17
Iteration 2(UML)
Read temperature inCelsius from keyboard
Convert temperaturefrom Celsius to Fahrenheit
Output Fahrenheittemperature to screen
Convert temperaturefrom Fahrenheit to Celsius
Output Celsiustemperature to screen
Read temperaturescale from keyboard
[ starts with C or c ] [ starts with F or f ]
Print errormessage
Decisionnode
Guardcondition
SE15: Loops(2) 10–18
Iteration 3(Pseudocode)
Repeat: Read a temperature from the keyboard
Read temperature scale from the keyboardIf temperature scale starts with ‘C’ or ‘c’: Convert temperature from Celsius to Fahrenheit Output Fahrenheit temperature to screenOtherwise if temperature scale starts with ‘F’ or ‘f’: Convert temperature from Fahrenheit to Celsius Output Celsius temperature to screenOtherwise: Print an error message on the screenAsk user whether another calculation is required
While user's response starts with ‘Y’ or ‘y’
SE15: Loops(2) 10–19
Iteration 3(UML) Read temperature
Read temp. scale
Convert to °Fand output
Print errormessage
Another conversion?
Convert to °Cand output
[ Y or y ]
[ C or c ] [ F or f ]
Merge node
SE15: Loops(2) 10–20
Your Turn!
How would you simplify Coursework 1? What would you attempt to do in your first iteration? What would the pseudocode / activity diagram look like?
SE15: Loops(2) 10–21
Iteration 1:Read numbers, stopping at –1
Read a number from the keyboardWhile the number last read is not equal to –1: Read another number from keyboard
int score = keyboard.nextInt();while (score != -1) { // Do stuff here... score = keyboard.nextInt();}
Read number
Compare with –1
Read anothernumber [ equal ]
[ not equal ]
SE15: Loops(2) 10–22
Summary
We have Looked at do-while loops Looked at tracing programs and debugging Seen how solutions can be expressed as pseudocode Looked at an alternative, graphical representation for
solutions: the UML activity diagram Emphasised the importance of writing readable code
SE15: Loops(2) 10–23
Follow-up Work
Reading from Savitch Section 3.3 (using pseudocode to specify loops) Section 2.4 (commenting and coding style)
Apply what you've learned today to Assignment 1 Go to the SE15 Off-Site Resources web page and visit
How NOT to do a programming assignment