Docsity

Iteration and Loops in Java: For, While, and Do-While Statements, Lecture notes of Computer Security

Partial preview of the text

Download Iteration and Loops in Java: For, While, and Do-While Statements and more Lecture notes Computer Security in PDF only on Docsity!

Iteration

Problem

 (^) Output the 7x table.

Counter-controlled Loops

 (^) Counter-controlled loops execute for a fixed number

of times.

 (^) A special counter variable is used to control the loop

and may be referred to within the loop.

 (^) Java provides the “for” statement as a counter-

controlled loop.

The “for” statement

for ( initialisation statement;

condition; increment statement )

{

statements …

}

Flowchart vs Java

int n;

for ( n=1; n<=12; n++ ) { System.out.println (n + “ x 7 = “ + (n*7)); }

Assign n=1 n <= 12?

Output (7*n)

no

yes n++

Additional “for” syntax

 (^) We can define a variable in the initialisation section,

which is local to the body of the loop.  (^) for ( int i=1; i<=10; i=i+1 )

 (^) Multiple comma-separated expressions can appear

in the “increment” section, even decrements.  (^) for (int i=10; i>0; i--)  (^) for (int i=1,j=7; i<=12; i++,j+=7)

Solution?

for ( int i=1; i<=12; i++ ) System.out.println (i+" x "+n+" = "+(n*i));

General Semantics of “for”

Initialisation Condition?

Statements

false

LOOP true

Incr.

Problem

 (^) Calculate ab^ using a for loop, assuming that a is a

float and b is an integer.

Nesting of statements

 (^) for and if are both statements, therefore they can

each appear within the statement body.

for ( int i=1; i<=10; i++ ) { if (a<b) max=b; }

if (a<b) { for (int i=1; i<=10; i++ ) ... }

for ( int i=1; i<=10; i++ ) for ( int j=1; j<=10; j++ )

Problem

 (^) Write programs to generate (on the screen) the

following triangles of user-specified height:

Condition-controlled Loops

 (^) If we do not know the number of iterations a priori (in

advance), we can use a condition-controlled (or event-controlled) loop - where the loop executes while a condition is true

 (^) Two statements:

while () { }

do { } while ()

Problem

 (^) Approximate the logarithm (with a base of 10) of an

integer using repeated division.

Problem

 (^) Approximate the logarithm (with a base of 10) of an

integer using repeated division.

 (^) Design a user interface where the user can continue

to ask for logarithms until a value of 0 is supplied.