0% found this document useful (0 votes)
47 views28 pages

Faizan Riaz Presentation

"While" loops condition true statement false a while statement has the following syntax: while (condition) (condition) statement; statement; if the condition is true, the statement is executed over and over until the condition becomes false. "Do while loops while" statement; condition; statement; if the condition is false, then the statement is evaluated again.

Uploaded by

Abdul Rehman
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views28 pages

Faizan Riaz Presentation

"While" loops condition true statement false a while statement has the following syntax: while (condition) (condition) statement; statement; if the condition is true, the statement is executed over and over until the condition becomes false. "Do while loops while" statement; condition; statement; if the condition is false, then the statement is evaluated again.

Uploaded by

Abdul Rehman
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 28

LOOPS

Presented By:

► Imran Khan
► Mohammad Fu’ad Mustafa
► Abdul Rehman
► Faizan Riaz
Overview
► Looping
 Introduction
► While loops
 Syntax
 Examples
► Infinite Loops
► Examples using while loops
► do.. while loops
 Examples
► For loops
 Definition
 Examples
 Readability
 Nesting
► Break – Continue
► Exiting
Introduction

► In the programs we have written so far, the statements in


the program have been executed in sequence, from the
start of the program to the end, omitting sections of "if"
and "switch" constructs which have not been selected.
The real power of computers comes from their ability to
execute given sets of statements many times, commonly
known as looping.
► In Programming we have three basic types of loops :
 The while loop
 The do while loop
 The for loop
Why Looping?

► (i) To automate the repetition of calculations. We wish to repeat


the calculation once for each one of a number of items of data. We may
wish to compute the profit for a number of different months of a
company's sales. We may wish to compute the stress in each part of the
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 the
calculation will need to be repeated.
► (ii) To iterate through data and test for certain condition. For
example, we may read numbers from a keyboard, analyze each one and
perform some action on it, until a particular value is typed. Another
example is that many computer programs keep reading commands and
executing them until the user types "quit". In this case, we do not know
in advance how many times we will have to go round the loop.
► (iii).To keep attempting for some operation (such as obtaining data
from a remote computer over a network) until either we succeed (all is
well, we have obtained the data, so we proceed to use that data), or until
a specified number of attempts have failed. (In this case the whole
process must be abandoned.)
"while" loops
false
condition

true
► A while statement has the
following syntax: statement

while (condition)
statement;

► If the condition is true, the statement is executed;


then the condition is evaluated again
► The statement is executed over and over until the
condition becomes false
"while" loops
int Number = 10;
while ( Number >= 0 ) {
System.out.println( "Number is " + Number );
Number--;
} // end while Number >= 0
System.out.println( "Loop ended");

► The condition to be tested is contained in parentheses


(round brackets) after the word "while", and the body of
the loop is in curly braces after the condition.
► There is no semicolon after the closing curly brace.
"while" loops
► The test is TRUE to continue the loop, FALSE to leave it. The test
occurs before the loop is executed; the loop may not be executed
at all if the test result is FALSE the very first time that it is
encountered. The pattern of execution is thus

test;
or
test; loop; test;
or
test; loop; test; loop, test;
and so on. The last test on each line must have delivered the
result FALSE; earlier tests must have delivered the result TRUE.

► When the loop finishes, control passes to the next instruction in


the program, following the closing curly brace of the loop.
While loops counting from 1 to 10
// version 1 // Version 3
int Number = 1; int Number = 0;
while ( Number <= 10 ) { while ( Number++ < 10 ) {
System.out.println( Number ); System.out.println( Number );
....; ....;
Number++; }
}
//version 2 // Version 4
int Number = 0; int Number = 0;
while ( Number < 10 ) { while ( ++Number <= 10 ) {
Number++; System.out.println( Number );
System.out.println( Number ); ....;
....; }
}
Infinite Loops

► The body of a while loop must eventually make the condition false
► If not, it is an infinite loop, which will execute until the user interrupts
the program
► This is a common type of logical error -- always double check that
your loops will terminate normally

int counter = 1
while (counter>0) {
System.out.println("Counter:" + counter);
counter++;
}
Examples of "while" loops
To add together the sequence 1 + 1/2 + 1/4 + 1/8 + ...
until the terms we are adding together are smaller than 0.00001
// We need float variables
float Term = 1.0f, Total = 0.0f;
int Counter = 0;
final float DELTA = 0.00001f;
while ( Term > DELTA ) {
// Add the next term to the total
Total += Term;
// Halve the term
Term /= 2.0; // or *= 0.5
// Count them
Counter++;
} // end while Term > 0.00001 loop
System.out.println( "Total " + Total );
System.out.println( "Number" + Counter );
“do” loops
► 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 the
statements in the body of the loop (and hence to execute the loop body always at
least once). In JAVA we use what is referred to as a "do" loop, written as follows:

int Number = 1;
do
{ ....;
Number++;
}
while ( Number <= 10 );

► In this case the value of "Number" would be 1 the first time round the loop, and
10 the last time. The condition (exactly as in a "while" loop) is still contained in
round brackets, and is still TRUE to continue with another execution of the loop
body, and FALSE to leave the loop. Remember that there is a semicolon after the
condition, terminating the whole statement. We have one more semicolon overall
than the equivalent "while" loop.
“do” loops

Syntax:
[initialization]
do {
[statements]
[iteration]
} while ( boolean-
expression )
“do” loops
► The pattern of execution in this case can be summarized as follows.
loop; test
loop; test; loop; test
loop; test; loop; test; loop; test
► The code in the above programming example could also be written
int Number = 1;
do {
....;
} while ( ++Number <= 10 );

► This is the form of combined "increment and test" that most C++
programmers that write JAVA would use. The "++" must, of course, be in
front of the "Number" in this case.
► It is generally safer to test at the start of a loop;
► "while" loops are generally safer and more common than "do" loops.
Examples of “do” loops
► Toread in positive numbers until a zero is encountered, and print the
biggest one.

int NextNumber, Biggest = 0;


do {
NextNumber = UserInput.readInt();
if ( Biggest < NextNumber ) {
Biggest = NextNumber;
}
} while ( NextNumber != 0 );
System.out.println( "Biggest " + Biggest );
Using System.exit()
► We may wish to abandon the program from within the body of the loop
if some error condition occurs.
int NextNumber;
do {
NextNumber = UserInput.readInt();
if ( NextNumber < 0 ) {
System.out.println( "Error, negative number" );
System.out.println( "Value " + NextNumber );
System.exit( -1 );
}
.. process the number ..
.. which must be >= 0 ..
} while ( NextNumber > 0 );
"for" loops
► The initialise statement is carried out once only, at the start of the
first time that the loop is entered.
► The test is executed before each execution of the body of the
loop, including a test before the very first execution of the loop.
► The first time will be immediately after the initialisation, and
hence there will be perhaps no executions of the loop body if the
test fails at this stage.
► The third expression is a statement executed after every
execution of the loop body, before the next test. It typically
increments a counter.
► The sequence is now :
init; test;
init; test; loop; incr; test;
init; test; loop; incr; test; loop; incr; test;
► Again note that the increments in the examples above could be
written with the "++" before or after the variable identifier; in this
case it does not matter.
"for" loops
Syntax:
for ([ initialization ];
[ boolean-expression ];
[iteration]) {
[statements]
}
Examples :
for ( Num = 10; Num > 0; Num--)
{
....;
}
for( Count = 0; Count < 10; Count++)
{
....;
}
"for" loops - Readability
► One of the important advantages of a "for" loop is its readability. All
of the essential loop control is grouped together at the top of the
loop. We can see at a glance the initial values which are set up, the
test to be satisfied for loop exit, and the main variable increments.
You should make maximum use of this readability.

► The "for" loop could be written as a "while" loop in the form :


declaration;
initialise;
....
while ( test ) {
....;
incr;
}
► In this layout, the loop control is not so clearly seen.
"for" loops
final float DELTA = 0.00001;
float term;
for ( term = 1.0; term > DELTA; term *= 0.5 ) {
....;
}

► It is common to declare the loop variable at the start of the for


loop itself :
for ( int Count = 0; Count < 10; Count++ ) {
....;
}
► The general form of a "for" loop is :
for ( initialise; test; execute after loop ) {
....;
}
Defaults
► Defaults are obvious;
► any or all of the three control statements can be omitted. The
construct
for ( ; ; ) {
....;
}
► gives no initialisation, assumes a TRUE test result, and performs
no incrementing.
► You may find the comma "operator" useful in the initialisation
and increment parts of the loop control.
for (
this = 10, that = 0;
this > that;
this--, that++
){
....;
}
General points on loops - Nesting
of loops
► Loops may, of course, be nested to any depth in any combination as
required.

for ( int year = 1900; year < 2000; year++ )


{
for ( int month = 0; month < 12; month++ )
{
....; // execute 1200 times ...
} // end month loop for each year
} // end year loop

► The loop executes with "month" and "year" taking the pairs of values
[1900,0], [1900,1], [1900,2], ..., [1900,11], [1901,0], [1901,1], ...,
[1901,11], ..., [1999,11] in turn in that order.
The "break" statement
► In any of the above loops, the special statement "break" causes
the loop to be abandoned, and execution continues following the
closing curly brace.
while ( i > 0 ) {
....;
if ( j == .... ) {
break; // abandon the loop
} ....;
} // end of the loop body
System.out.println( "continues here ...");
► The program continues after the end of the loop.
► Within a nested loop, "break" causes the inner most loop to be
abandoned.
The "continue" statement

► In any of the above loops, the statement "continue"


causes the rest of the current round of the loop to be
skipped, and a "while" or "do" loop moves directly to
the next test at the head or foot of the loop,
respectively;
► a "for" loop moves to the increment expression, and
then to the test.
► Note that labeled break and continue are available
but beyond the scope of this course.
Example of "break" and
"continue"
► We wish to write a loop processing integer values which we have read in. If the
value we have read is negative, we wish to print an error message and abandon
the loop. If the value read is greater than 100, we wish to ignore it and continue
to the next value in the data. If the value is zero, we wish to terminate the loop.
while ( ( value = UserInput.readInt() ) != 0 )
{
if ( value < 0 ) {
System.out.println( "Illegal value");
break; // Abandon the loop
}
If ( value > 100 )
{
System.out.println( "Invalid value");
continue; // Skip to start loop again
}
// Process the value read
// guaranteed between 1 and 100
....;
....;
} / end while value != 0
“for” loops
► Comments : It is good practice to comment the
end closing curly brace of any loop which
extends over more than a few lines.
The CourseMaster system expects a comment
after every closing brace which appears more
than 10 lines from its opening curly brace.
► Curly braces : If there is only a single
statement in the loop body, the curly braces are
not obligatory in JAVA. It is however
recommended that you always use them.
References

► Wikipedia.com
► Google.com
► Scrab.com
Thanks for Paying
Attention

You might also like