Download - Faizan Riaz Presentation
-
8/8/2019 Faizan Riaz Presentation
1/28
LOOPSLOOPS
-
8/8/2019 Faizan Riaz Presentation
2/28
Presented By:Presented By:
Imran KhanImran Khan
Mohammad Fuad MustafaMohammad Fuad Mustafa
Abdul RehmanAbdul Rehman
Faizan RiazFaizan Riaz
-
8/8/2019 Faizan Riaz Presentation
3/28
OverviewOverview LoopingLooping
IntroductionIntroduction While loopsWhile loops
SyntaxSyntax
ExamplesExamples
Infinite LoopsInfinite Loops
Examples using while loopsExamples using while loops do.. while loopsdo.. while loops
ExamplesExamples
For loopsFor loops
DefinitionDefinition
ExamplesExamples
ReadabilityReadability
NestingNesting
BreakBreak ContinueContinue
ExitingExiting
-
8/8/2019 Faizan Riaz Presentation
4/28
IntroductionIntroduction
In the programs we have written so far, the statements inIn the programs we have written so far, the statements inthe program have been executed in sequence, from thethe program have been executed in sequence, from the
start of the program to the end, omitting sections of "start of the program to the end, omitting sections of "ifif
""and "and "switchswitch" constructs which have not been selected." constructs which have not been selected.
The real power of computers comes from their ability toThe real power of computers comes from their ability toexecute given sets of statements many times, commonlyexecute given sets of statements many times, commonlyknown as looping.known as looping.
In Programming we have three basic types of loops :In Programming we have three basic types of loops : TheThe whilewhile looploop
TheThe do whiledo while looploop
TheThe forfor looploop
-
8/8/2019 Faizan Riaz Presentation
5/28
Why Looping?Why Looping?
(i)(i) To automate the repetition of calculationsTo automate the repetition of calculations. We wish to repeat. We wish to repeatthe calculation once for each one of a number of items of data. We maythe calculation once for each one of a number of items of data. We maywish to compute the profit for a number of different months of awish to compute the profit for a number of different months of acompany's sales. We may wish to compute the stress in each part of thecompany's sales. We may wish to compute the stress in each part of thestructure of a bridge. We may wish to look at each word in a file of text.structure of a bridge. We may wish to look at each word in a file of text.
In some cases, we may know in advance exactly how many times theIn some cases, we may know in advance exactly how many times thecalculation will need to be repeated.calculation will need to be repeated.
(ii)(ii) To iterate through data and test for certain condition.To iterate through data and test for certain condition. ForForexample, we may read numbers from a keyboard, analyze each one andexample, we may read numbers from a keyboard, analyze each one andperform some action on it, until a particular value is typed. Anotherperform some action on it, until a particular value is typed. Anotherexample is that many computer programs keep reading commands andexample is that many computer programs keep reading commands andexecuting them until the user types "quit". In this case, we do not knowexecuting them until the user types "quit". In this case, we do not knowin advance how many times we will have to go round the loop.in advance how many times we will have to go round the loop.
(iii).(iii).To keep attempting for some operationTo keep attempting for some operation (such as obtaining data(such as obtaining datafrom a remote computer over a network) until either we succeed (all isfrom a remote computer over a network) until either we succeed (all iswell, we have obtained the data, so we proceed to use that data), or untilwell, we have obtained the data, so we proceed to use that data), or untila specified number of attempts have failed. (In this case the wholea specified number of attempts have failed. (In this case the wholeprocess must be abandoned.)process must be abandoned.)
-
8/8/2019 Faizan Riaz Presentation
6/28
"while" loops"while" loops
AA while statementwhile statement has thehas thefollowing syntax:following syntax:
while (while (conditioncondition))
statementstatement;;
If the condition is true, the statement is executed;If the condition is true, the statement is executed;then the condition is evaluated againthen the condition is evaluated again
The statement is executed over and over until theThe statement is executed over and over until thecondition becomes falsecondition becomes false
statement
condition
false
true
-
8/8/2019 Faizan Riaz Presentation
7/28
""whilewhile" loops" loops
int Number = 10;int Number = 10;
while ( Number >= 0 ) {while ( Number >= 0 ) {
System.out.println( "Number is " + Number );System.out.println( "Number is " + Number );
NumberNumber----;;
} // end while Number >= 0} // end while Number >= 0
System.out.println( "Loop ended");System.out.println( "Loop ended");
The condition to be tested is contained in parenthesesThe condition to be tested is contained in parentheses(round brackets) after the word(round brackets) after the word "while","while", and the body ofand the body of
the loop is in curly braces after the condition.the loop is in curly braces after the condition.
There is no semicolon after the closing curly brace.There is no semicolon after the closing curly brace.
-
8/8/2019 Faizan Riaz Presentation
8/28
""whilewhile" loops" loops
The test is TRUE to continue the loop, FALSE to leave it. The testThe test is TRUE to continue the loop, FALSE to leave it. The testoccurs before the loop is executed; the loop may not be executedoccurs before the loop is executed; the loop may not be executedat all if the test result is FALSE the very first time that it isat all if the test result is FALSE the very first time that it isencountered. The pattern of execution is thusencountered. The pattern of execution is thus
test;test;oror
test; loop; test;test; loop; test;
oror
test; loop; test; loop, test;test; loop; test; loop, test;
and so on. The last test on each line must have delivered theand so on. The last test on each line must have delivered theresult FALSE; earlier tests must have delivered the result TRUE.result FALSE; earlier tests must have delivered the result TRUE.
When the loop finishes, control passes to the next instruction inWhen the loop finishes, control passes to the next instruction inthe program, following the closing curly brace of the loop.the program, following the closing curly brace of the loop.
-
8/8/2019 Faizan Riaz Presentation
9/28
While loops counting from 1 to 10While loops counting from 1 to 10
// version 1// version 1int Number = 1;int Number = 1;
while ( Number
-
8/8/2019 Faizan Riaz Presentation
10/28
Infinite LoopsInfinite Loops
The body of aThe body of a whilewhileloop must eventually make the condition falseloop must eventually make the condition false
If not, it is anIf not, it is an infinite loopinfinite loop, which will execute until the user interrupts, which will execute until the user interrupts
the programthe program This is a common type of logical errorThis is a common type of logical error ---- always double check thatalways double check that
your loops will terminate normallyyour loops will terminate normally
int counter = 1int counter = 1
while (counter>0) {while (counter>0) {
System.out.println("Counter:" + counter);System.out.println("Counter:" + counter);
counter++;counter++;
}}
-
8/8/2019 Faizan Riaz Presentation
11/28
Examples ofExamples of"while""while" loopsloops
To add together the sequence 1 + 1/2 + 1/4 + 1/8 + ...To add together the sequence 1 + 1/2 + 1/4 + 1/8 + ...
until the terms we are adding together are smaller than 0.00001until the terms we are adding together are smaller than 0.00001
// Weneed float variables// Weneed float variables
float Term = 1.0f, Total = 0.0f;float Term = 1.0f, Total = 0.0f;
intCounter = 0;intCounter = 0;
finalfloat DELTA = 0.00001f;finalfloat DELTA = 0.00001f;while ( Term > DELTA ) {while ( Term > DELTA ) {
// Add thenexttermto thetotal// Add thenexttermto thetotal
Total += Term;Total += Term;
// Halvetheterm// Halvetheterm
Term/= 2.0;// or *= 0.5Term/= 2.0;// or *= 0.5
//Countthem//Countthem
Counter++;Counter++;
}//end while Term > 0.00001 loop}//end while Term > 0.00001 loop
System.out.println( "Total" + Total);System.out.println( "Total" + Total);
System.out.println( "Number" + Counter );System.out.println( "Number" + Counter );
-
8/8/2019 Faizan Riaz Presentation
12/28
dodo loopsloops The "while" loops above performed the test first, and then executed the loop.The "while" loops above performed the test first, and then executed the loop.
Sometimes you may wish to test at the end of the loop, after the execution of theSometimes you may wish to test at the end of the loop, after the execution of thestatements in the body of the loop (and hence to execute the loop body always atstatements in the body of the loop (and hence to execute the loop body always atleast once). In JAVA we use what is referred to as a "do" loop, written as follows:least once). In JAVA we use what is referred to as a "do" loop, written as follows:
intNumber = 1;intNumber = 1;
dodo
{ ....;{ ....;
Number++;Number++;
}}
while ( Number
-
8/8/2019 Faizan Riaz Presentation
13/28
dodo loopsloops
Syntax:Syntax:[initialization][initialization]
do {do {
[statements][statements]
[iteration][iteration]
}while ( boolean}while ( boolean--
expression)expression)
-
8/8/2019 Faizan Riaz Presentation
14/28
dodo loopsloops
The pattern of execution in this case can be summarized as follows.The pattern of execution in this case can be summarized as follows.loop; testloop; test
loop; test; loop; testloop; test; loop; test
loop; test; loop; test; loop; testloop; test; loop; test; loop; test
The code in the above programming example could also be writtenThe code in the above programming example could also be writtenintNumber = 1;intNumber = 1;
do {do {
....;....;
}while ( ++Number
-
8/8/2019 Faizan Riaz Presentation
15/28
Examples ofExamples ofdodo loopsloops
To read in positive numbers until a zero isTo read in positive numbers until a zero isencountered, and print the biggest one.encountered, and print the biggest one.
intNextNumber, Biggest = 0;intNextNumber, Biggest = 0;
do {do {
NextNumber = UserInput.readInt();NextNumber = UserInput.readInt();
if ( Biggest < NextNumber ) {if ( Biggest < NextNumber ) {
Biggest = NextNumber;Biggest = NextNumber;
}}
}while ( NextNumber != 0 );}while ( NextNumber != 0 );
-
8/8/2019 Faizan Riaz Presentation
16/28
UsingUsing System.exit()System.exit()
We may wish to abandon the program from within the body of the loopWe may wish to abandon the program from within the body of the loopif some error condition occurs.if some error condition occurs.intNextNumber;intNextNumber;
do {do {
NextNumber = UserInput.readInt();NextNumber = UserInput.readInt();
if ( NextNumber < 0 ) {if ( NextNumber < 0 ) {
System.out.println( "Error,negativenumber");System.out.println( "Error,negativenumber");
System.out.println( "Value" + NextNumber );System.out.println( "Value" + NextNumber );
System.exit(System.exit( --1 );1 );
}}
..process thenumber ....process thenumber ..
..whichmust be >= 0 ....whichmust be >= 0 ..
}while ( NextNumber > 0 );}while ( NextNumber > 0 );
-
8/8/2019 Faizan Riaz Presentation
17/28
"for""for" loopsloops The initialise statement is carried out once only, at the start of theThe initialise statement is carried out once only, at the start of the
first time that the loop is entered.first time that the loop is entered. The test is executed before each execution of the body of theThe test is executed before each execution of the body of the
loop, including a test before the very first execution of the loop.loop, including a test before the very first execution of the loop. The first time will be immediately after the initialisation, andThe first time will be immediately after the initialisation, and
hence there will be perhaps no executions of the loop body if thehence there will be perhaps no executions of the loop body if the
test fails at this stage.test fails at this stage. The third expression is a statement executed after everyThe third expression is a statement executed after every
execution of the loop body, before the next test. It typicallyexecution of the loop body, before the next test. It typicallyincrements a counter.increments a counter.
The sequence is now :The sequence is now :init; test;init; test;
init; test; loop; incr; test;init; test; loop; incr; test;init; test; loop; incr; test; loop; incr; test;init; test; loop; incr; test; loop; incr; test;
Again note that the increments in the examples above could beAgain note that the increments in the examples above could bewritten with the "++" before or after the variable identifier; in thiswritten with the "++" before or after the variable identifier; in thiscase it does not matter.case it does not matter.
-
8/8/2019 Faizan Riaz Presentation
18/28
"for""for" loopsloops
Syntax:Syntax:for ([initialization];for ([initialization];[ boolean[ boolean--expression];expression];
[iteration]) {[iteration]) {
[statements][statements]
}}
Examples :Examples :
for ( Num = 10;Num > 0;Numfor ( Num = 10;Num > 0;Num----))
{{
....;....;
}}
for( Count = 0;Count < 10;Count++)for( Count = 0;Count < 10;Count++)
{{
....;....;
}}
-
8/8/2019 Faizan Riaz Presentation
19/28
"for""for" loopsloops -- ReadabilityReadability
One of the important advantages of a "for" loop is its readability. AllOne of the important advantages of a "for" loop is its readability. Allof the essential loop control is grouped together at the top of theof the essential loop control is grouped together at the top of theloop. We can see at a glance the initial values which are set up, theloop. We can see at a glance the initial values which are set up, thetest to be satisfied for loop exit, and the main variable increments.test to be satisfied for loop exit, and the main variable increments.
You should make maximum use of this readability.You should make maximum use of this readability.
The "for" loop could be written as a "while" loop in the form :The "for" loop could be written as a "while" loop in the form :declaration;declaration;
initialise;initialise;
........
while ( test) {while ( test) {....;....;
incr;incr;
}}
In this layout, the loop control is not so clearly seen.In this layout, the loop control is not so clearly seen.
-
8/8/2019 Faizan Riaz Presentation
20/28
"for""for" loopsloops
finalfloat DELTA = 0.00001;finalfloat DELTA = 0.00001;
floatterm;floatterm;
for ( term = 1.0;term > DELTA;term *= 0.5) {for ( term = 1.0;term > DELTA;term *= 0.5) {
....;....;
}}
It is common to declare the loop variable at the start of the forIt is common to declare the loop variable at the start of the forloop itself :loop itself :
for ( intCount = 0;Count < 10;Count++ ) {for ( intCount = 0;Count < 10;Count++ ) {
....;....;
}}
The general form of a "for" loop is :The general form of a "for" loop is :for ( initialise;test;execute after loop) {for ( initialise;test;execute after loop) {
....;....;
}}
-
8/8/2019 Faizan Riaz Presentation
21/28
DefaultsDefaults Defaults are obvious;Defaults are obvious; any or all of the three control statements can be omitted. Theany or all of the three control statements can be omitted. The
constructconstructfor ( ;;) {for ( ;;) {
....;....;
}}
gives no initialisation, assumes a TRUE test result, and performsgives no initialisation, assumes a TRUE test result, and performsno incrementing.no incrementing. You may find the comma "operator" useful in the initialisationYou may find the comma "operator" useful in the initialisation
and increment parts of the loop control.and increment parts of the loop control.for (for (
this = 10,that = 0;this = 10,that = 0;
this > that;this > that;thisthis----,that++,that++
){){
....;....;
}}
-
8/8/2019 Faizan Riaz Presentation
22/28
General points on loopsGeneral points on loops -- NestingNesting
of loopsof loops Loops may, of course, be nested to any depth in any combination asLoops may, of course, be nested to any depth in any combination as
required.required.
for ( int year = 1900; year < 2000; year++ )for ( int year = 1900; year < 2000; year++ )
{{
for ( intmonth = 0;month < 12;month++ )for ( intmonth = 0;month < 12;month++ )
{{
....;....; //execute 1200 times ...//execute 1200 times ...
}} //end monthloopfor each year//end monthloopfor each year
}} //end year loop//end year loop
The loop executes with "month" and "year" taking the pairs ofvaluesThe loop executes with "month" and "year" taking the pairs ofvalues[1900,0], [1900,1], [1900,2], ..., [1900,11], [1901,0], [1901,1], ...,[1900,0], [1900,1], [1900,2], ..., [1900,11], [1901,0], [1901,1], ...,[1901,11], ..., [1999,11] in turn in that order.[1901,11], ..., [1999,11] in turn in that order.
-
8/8/2019 Faizan Riaz Presentation
23/28
TheThe "break""break" statementstatement
In any of the above loops, the special statement "In any of the above loops, the special statement "breakbreak" causes" causes
the loop to be abandoned, and execution continues following thethe loop to be abandoned, and execution continues following theclosing curly brace.closing curly brace.
while ( i > 0 ) {while ( i > 0 ) {
....;....;
if ( j == ....) {if ( j == ....) {
break;// abandontheloopbreak;// abandontheloop
}....;}....;
}//end oftheloop body}//end oftheloop body
System.out.println( "continues here...");System.out.println( "continues here...");
The program continues after the end of the loop.The program continues after the end of the loop.
Within a nested loop, "break" causes the inner most loop to beWithin a nested loop, "break" causes the inner most loop to beabandoned.abandoned.
-
8/8/2019 Faizan Riaz Presentation
24/28
TheThe "continue""continue" statementstatement
In any of the above loops, the statement "In any of the above loops, the statement "continuecontinue""
causes the rest of the current round of the loop to becauses the rest of the current round of the loop to beskipped, and a "skipped, and a "whilewhile" or "" or "dodo" loop moves directly to" loop moves directly to
the next test at the head or foot of the loop,the next test at the head or foot of the loop,respectively;respectively;
a "a "forfor" loop moves to the increment expression, and" loop moves to the increment expression, and
then to the test.then to the test.
Note that labeledNote that labeled breakbreak andand continuecontinue are availableare availablebut beyond the scope of this course.but beyond the scope of this course.
-
8/8/2019 Faizan Riaz Presentation
25/28
Examp e oExamp e o "break""break" anan"continue""continue"
We wish to write a loop processing integer values which we have read in. If theWe wish to write a loop processing integer values which we have read in. If thevalue we have read is negative, we wish to print an error message and abandonvalue we have read is negative, we wish to print an error message and abandonthe loop. If the value read is greater than 100, we wish to ignore it and continuethe loop. If the value read is greater than 100, we wish to ignore it and continueto the nextvalue in the data. If the value is zero, we wish to terminate the loop.to the nextvalue in the data. If the value is zero, we wish to terminate the loop.while ( ( value = UserInput.readInt()) != 0 )while ( ( value = UserInput.readInt()) != 0 )
{{
if ( value < 0 ) {if ( value < 0 ) {
System.out.println( "Illegal value");System.out.println( "Illegal value");break;break; // Abandontheloop// Abandontheloop
}}
If ( value > 100 )If ( value > 100 )
{{
System.out.println( "Invalid value");System.out.println( "Invalid value");
continue;continue; // Skipto startloop again// Skipto startloop again
}}
// Process the value read// Process the value read
//guaranteed between 1 and 100//guaranteed between 1 and 100
....;....;
....;....;
}} /end while value != 0/end while value != 0
-
8/8/2019 Faizan Riaz Presentation
26/28
forfor loopsloops
Comments :Comments : It is good practice to comment theIt is good practice to comment theend closing curly brace of any loop whichend closing curly brace of any loop whichextends over more than a few lines.extends over more than a few lines.The CourseMaster system expects a commentThe CourseMaster system expects a comment
after every closing brace which appears moreafter every closing brace which appears morethan 10 lines from its opening curly brace.than 10 lines from its opening curly brace.
Curly braces :Curly braces : If there is only a singleIf there is only a singlestatement in the loop body, the curly braces arestatement in the loop body, the curly braces are
not obligatory in JAVA. It is howevernot obligatory in JAVA. It is howeverrecommended that you always use them.recommended that you always use them.
-
8/8/2019 Faizan Riaz Presentation
27/28
ReferencesReferences
Wikipedia.comWikipedia.com
Google.comGoogle.com
Scrab.comScrab.com
-
8/8/2019 Faizan Riaz Presentation
28/28
Thanks for PayingThanks for PayingAttentionAttention