Upload
phamdang
View
242
Download
0
Embed Size (px)
Citation preview
DCS/100: Procedural ProgrammingWeek 5: While Loops
Queen Mary, University of London
DCS/100: wk 5 – p.1/33
Last week
You should now be able to:
write programs that follow instructions a known numberof times
explain what is meant by a for loop
trace the execution of programs containing for loops
DCS/100: wk 5 – p.2/33
A program from last week
int sum = 0;for (int i=1; i<=5; i++){
sum = sum + i;}out.writeln("Total is "+ sum);
DCS/100: wk 5 – p.3/33
This week
At the end of this week you will be able to:
write programs that follow instructions repeatedly wherethe number of times is not known at the outset
explain what is meant by for loops and while loops, theirsimilarities and differences
trace the execution of programs containing loops
DCS/100: wk 5 – p.4/33
While loops
Loops generally have two parts:
a test to tell you whether to do it again
a thing to be done repeatedly
There is also always something that is changed by theaction of the loop.
When writing loops always work out these parts first.
DCS/100: wk 5 – p.5/33
While loops
You do not always know how many times to repeat...A pure for loop is then little help.
Let us invent a new loop construct...
We need to tell the computer
what is to be repeated,
do we stop yet?
while (<a test about continuing is true>){
<do these instructions over and over>}
DCS/100: wk 5 – p.6/33
While Loops
char ans=’y’;
while (ans==’y’){
out.writeln("I did it!");out.write("Shall I go on? (y/n) ");ans = in.read();in.readln();
}
DCS/100: wk 5 – p.7/33
While loops
Format:while (<condition>) <body>
Check <condition>;if true do <body>,go back, check <condition>;if true do <body>,go back, check <condition>;if true do <body>,. . . until <condition> is false
If <condition> is false initially, <body> is never exe-
cuted.
DCS/100: wk 5 – p.8/33
While loops
Can go on for ever:while (true){}Stop by typing Ctrl-C (Control-C).
DCS/100: wk 5 – p.9/33
While loops and accumulators
Often use accumulator variables with while loops too:int count=0;char ans = ’y’;
while (ans==’y’){ count = count+1;
out.write("Shall I go on? (y/n) ");ans = in.read();in.readln();
}out.writeln("That was "+count+" times");
DCS/100: wk 5 – p.10/33
Another Accumulator
int ans=0;
int count=0,sum=0;
out.write("Enter a number (eof to terminate): ");
while (in.digit())
{ ans = in.readint();
count = count+1;
sum = sum+ans;
out.write("Enter a number
(eof to terminate): ");
in.readblanks();
}
out.writeln("That was "+count+" numbers");
out.writeln("with a sum of "+sum);
out.writeln("and an average
of "+((double) sum/ (double) count));
DCS/100: wk 5 – p.11/33
While loops
Of course you can wrap a while loop round lots of theprevious exercises, so that you can do something a numberof times:char ans=’y’;
while (ans==’y’){
<program goes here>
out.write("Another? (y/n) ");ans = in.read();in.readln();
}
DCS/100: wk 5 – p.12/33
Beware
You have to make sure that the program you drop in readsall of any input it calls for, including any newlines!
This is typical in Computer Science: some operation only
works if the thing you apply it to is well-behaved in some
way: it obeys some “protocol”.
DCS/100: wk 5 – p.13/33
While loops and structured programming
This illustrates the “structured” approach.
Be clear about what the body of a loop is supposed todo. Develop it as an entity in its own right.
Brinch Hansen’s approach:
Program is a sequence of (named) subtasks.
Develop the subtasks be refining them towards code.
As you do this put in if statements and loops.
Branches of if’s and bodies of loops are subtasks.
DCS/100: wk 5 – p.14/33
While loops and for loops
Any standard for loop can be programmed up using a whileloop:for (int i=<start>; i <= <finish>; i++){
<body>}is the same as{int i=<start>;while (i <= <finish>){
<body>i++;
}}
DCS/100: wk 5 – p.15/33
While loops and for loops
The reverse is not true.
While loops cannot be programmed up as standard forloops.
Evidence: It’s easy to write non-terminating programsusing while loops. You can’t do this if you only use standardfor loops.
DCS/100: wk 5 – p.16/33
While loops and for loops
The C/Java for loop is more general. It is equivalent to whileloops.A general Java for loop:
for (<init>;<test>;<reinit>) <body>
means:first do <init>,then if <test> is true do <body>then do <reinit> and return to the start of the loopif <test> is true do <body>then do <reinit> and return to the start of the loop. . .
until test is false.DCS/100: wk 5 – p.17/33
While loops and for loops
for (<init>;<test>;<reinit>) <body>means:
1. do <init>,
2. evaluate <test>
3. if <test> is true(a) do <body>
(b) do <reinit>
(c) return to stage 2otherwise end the loop and carry on with the rest of theprogram.
DCS/100: wk 5 – p.18/33
While loops and for loops
So
for (<init>;<test>;<reinit>) <body>
is equivalent to
{ <init>;while (<test>){
<body><reinit>
}}
DCS/100: wk 5 – p.19/33
While loops and for loops
But a general while loop:while (<test>) <body>
is equivalent to
for ( ; <test>; ) <body>
So in Java (and C/C++) anything you can write with while
you can write with for and vice versa.
DCS/100: wk 5 – p.20/33
The basic control constructs
Sequence: do this, then do that.In Java this is done just by writing one command afteranother.
Branching: choose between different things.In Java this isif (<test>) <case> else <case>(and the switch construct).
DCS/100: wk 5 – p.21/33
The basic control constructs
Looping: keep repeating something until some exitcondition is met. There’s a difference between “forloops” (do something a fixed number of times) and“while loops”In Java:for (int i=<start>; i<=<finish>; i++)<body>while (<test>) <body>for (<init>;<test>;<reinit>) <body>
DCS/100: wk 5 – p.22/33
Basic Control Constructs
THAT’S IT.THERE ARE NO MORE BASICCONTROL CONSTRUCTS!!!!
A language that has these control constructs is“Turing complete”. You can write any computableoperation in it.
DCS/100: wk 5 – p.23/33
Basic Control Constructs
Everything else is there for other reasons
to make the language clearer
to allow you to break up code better
to make code easier to reuse
to make programs easier to develop
to make programs more secure in their running
. . .
DCS/100: wk 5 – p.24/33
Debugging
Most of you are getting code that compiles.
But what do you do when it doesn’t work?
DCS/100: wk 5 – p.25/33
Debugging
First Step
INDENT YOUR CODE PROPERLY
Execution follows the grammatical structure of code.
Indentation makes that structure visible.
It lets you see where choice points are.
It lets you break the program up into phases.
It lets you see what bits you can comment out.
It often makes it obvious if you’ve put something simple(a read(), a writeln()) in the wrong place (inside oroutside a loop).
DCS/100: wk 5 – p.26/33
Debugging
First Step
INDENT YOUR CODE PROPERLY
You should indent your code properly as you write it.
This stops some of the mistakes ever happening.
DCS/100: wk 5 – p.27/33
Proper indentation
See Brinch Hansen 59-61
See Jon Rowson’s layout notesThe two crucial points:
indent blocks a fixed amount
make ends line up with beginnings
DCS/100: wk 5 – p.28/33
Proper indentation
The two crucial points:
indent blocks a fixed amount
make ends line up with beginnings
Brinch Hansen: end bracket of block lines up with beginningbracket.
Rowson: end bracket of block lines up with enlosing if,while, for, switch.
DCS/100: wk 5 – p.29/33
Proper indentation
Advanced editors (eg emacs) give machine support forindentation.
DCS/100: wk 5 – p.30/33
Debugging
Second step
LOCALISE THE PROBLEM
Put in print statements to tell you how you are goingthrough the code.out.writeln("We got to here");
Print out values of variables, so that you can comparethem with what you expect.
Use these to find out where in the program the problemis.
DCS/100: wk 5 – p.31/33
Debugging
Third step
FIX THE PROBLEM
Once you have the problem localised, put in more printstatements systematically so that you can trace thecode.
Use your knowledge of what the program is actuallydoing versus what it should be doing to fix it.
DCS/100: wk 5 – p.32/33
This Week
By the end of the week you should be able to:
write programs that follow instructions repeatedly wherethe number of times is not known at the outset
explain what is meant by for loops and while loops, theirsimilarities and differences
trace the execution of programs containing loops
ReadingBrinch Hansen chapters 4 and 5.Computing Without Computers chapter 6 (ignoring sectionson “recursion” for now)
DCS/100: wk 5 – p.33/33