Textbook Notes (280,000)
CA (170,000)
Ryerson (10,000)
ITM (900)
ITM 200 (20)
Chapter 6

Chapter 6

Information Technology Management
Course Code
ITM 200
Vikraman Baskaran

This preview shows page 1. to view the full 5 pages of the document.
Chapter 6 – Repetition using loops
6.1 A problem
To write a method to output the statementI must practice my programming” 100 times
Set a counter to 1
While the counter is <= 100
Print the important info
Add 1 to the counter
In Java, it would look like
oPublic static void lines (Strings [] args) {
int counter;
counter = 1;
while (count <= 10) {
System.out.println(“I must practice my programming”);
counter = counter + 1; }
The while loop statement – the details
Syntax of the Java while loop statement is as follows
owhile (<TEST>)
While is a Java reserved word, which tells the compiler that this is a while loop statement
(<TEST>) is a Boolean expression, it must be enclosed in parentheses
<STATEMENT> is any Java statement, known as body of the loop
You're Reading a Preview

Unlock to view full version

Only page 1 are available for preview. Some parts have been intentionally blurred.

<STATEMENT> can be compound statement, in other words several Java statements
surrounded by { }
Semantics of the while loop statement
When while loop starts, first thing happens is that <TEST> is evaluated, if <TEST> has
false then <STATEMENT> is not performed and control passes to the next statement in
the program following the while loop
If <TEST> is true then <STATEMENT> is performed and <TEST> is evaluated again
and if it is still true then <STATEMENT> is performed again
This cycle of evaluating <TEST> and performing <STATEMENT> continues until
<TEST> evaluates to false
6.2 Counter-controlled loops
Loops often use some form of counter variable also called a controlled variable to
determine how many times the loop should be performed
This counter must be initialized (given a starting value) before the loop is entered, for
oint counter;
ocounter = 1;
A counter declaration and initialization can be combined, for example
oint counter = 1;
Counter-control pattern
counter = <start value>;
while (counter <= <finish value>)
o<instructions to be repeated>
ocounter = counter + <increment>;
The loop is performed a fixed # of times, controlled by the control variable
You're Reading a Preview

Unlock to view full version