0% found this document useful (0 votes)
22 views

INFO6066 - Repetition (Loop) Control Structures

The document discusses the three main types of loops in Java: for loops, while loops, and do-while loops. It provides details on how each loop works, including syntax, loop continuation conditions, and examples of each type of loop. The document also covers other loop-related concepts like break and continue.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

INFO6066 - Repetition (Loop) Control Structures

The document discusses the three main types of loops in Java: for loops, while loops, and do-while loops. It provides details on how each loop works, including syntax, loop continuation conditions, and examples of each type of loop. The document also covers other loop-related concepts like break and continue.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 24

INFO 6066 Coding For Test

Java’s 3 Loops:
For, while, do-while and the (for: each) structure

INFO 6066
Repetition (or Iteration) Statements: Loops
• Used to repeat a segment of code until a certain condition is met.
• Three main types of loops in Java:
• 1) for loop
• 2) while loop
• 3) do while loop

• As of JDK 1.5, There is also a (for:each) loop structure that can be used
with advanced data structures such as arrays, lists, and vectors. We’ll look
at it briefly when we do some work with arrays.

INFO 6066
Two Types of Loop Situations: Indeterminate vs
Determinate

• Indeterminate loop situations are those situations where we do not know


in advance how many times we may have to repeat (or iterate) the loop
body code. (T!)
• Example: a data validation loop, where we check the value a user has
entered before we go on to the next part of a program.
• If the user is really dumb (not uncommon in our business) then they may
repeatedly enter bad data several times, so we keep telling them to “Please
enter your data again…”
• In this case, our loop may run only once, or many times depending on the
user’s IQ…
• Type of loop favoured for indeterminate situations: usually we’ll use a
while loop or a do-while loop for these indeterminate loop situations. (T!)

INFO 6066
Determinate Loop Situations
• In a determinate loop situation we know ahead of time exactly how many
iterations our loop body code has to iterate.
• Example: asking a user how many test scores they will be entering into a
marks averager program.
• If the user has ten marks to enter, then we know that our loop that asks
them to enter each test score must run exactly 10 times.
• Type of loop favoured for determinate situations: usually we’ll use a for
loop for these situations, although you can also use a counter-controlled
while loop as well. (T!)

INFO 6066
The while loop: a pre-test type of loop

• In a while loop, the loop continuation condition (LCC) is checked


first before trying to run the loop body statements.
• The LCC evaluates to a boolean value of true or false
• If the LCC is true, then we execute the loop body code.
• If the LCC evaluates to false, then we skip the loop body code.
• Syntax is:
while( some condition here) //loop continuation condition
{
//loop body statement(s);
} //end while

• Note: you need to include in the loop body something to eventually


cause the loop continuation condition to become false, otherwise
you get an infinite loop. (T!)

INFO 6066
while Loop that is controlled by a counter…

• int num1 = 1;
• int sum = 0;
while (sum < 5)
{
sum = sum + num1; // increments loop cont. condition
}//end while
• Here, the variable sum is the LCC control variable
• sum gets incremented each time so that loop eventually ends
• When value of sum hits 5, the loop continuation condition is false
and the loop terminates.
• while loop can also be used when exact number of repetitions
needed may not be known in advance.

INFO 6066
while Example
• Example – Using a sentinel value

• A program adds up all the numbers that user enters.

• This program uses an entry of zero as a sentinel value to end the loop.

• Sentinel- dictionary definition is a sentinel is a guard or watchman.

• When a sentinel value of zero is entered, the while loop continuation


condition becomes false, and the loop terminates or ends.

INFO 6066
While Loop Using a Sentinel Value

• This loop will accept user input until the user enters a value of 0…
• Scanner input = new Scanner(System.in);
int sum = 0;
int userInput = -1; //set this to a non-zero value so loop will start
while( userInput != 0) //while userInput is NOT EQUAL to zero…
{
System.out.print(“Enter the next value…);
userInput = input. nextInt(); //read the keyboard
sum = sum + userInput; //add input to the sum
} //end while

INFO 6066
The do-while loop: a post-test type of loop.
• In a do-while loop, the loop body code is run first and the LCC condition is checked
after the body code has run. This is called a post-test check.
• int counter = 0;
int limit = 25;
do
{
//loop body statement(s);
counter++; //increment the counter by one
} while (counter < limit);
• Difference from the while loop is this: In a do-while loop, the
loop body statement(s) will ALWAYS run at least once, because condition is
checked after the loop body executes.(T!)
• Again, the counter control variable must be able to change so loop can eventually
terminate.
• The do-while loop is often used as a data-validation loop since it is guaranteed to
run at least once. (T!)

INFO 6066
Infinite while loop using the ‘break’ keyword
• This is often seen in while loops:
while(true)
{
//exit condition if i equals 12
if (i ==12)
break;
}
• This loop will loop repeatedly until a loop exit condition specified inside the
block is met.
• Loop exit is accomplished using the break keyword…more on this a little
later.

INFO 6066
for Loop
• Steps in setting up a for loop:
• 1) set the initial conditions for the loop and create and initialize the loop
control variable
• 2) specify the condition for the loop to continue. This is called the loop
continuation condition. (T!)
• 3) arrange it so that the loop control variable gets incremented after each
iteration of the loop.

• The for loop is used when we know in advance how many times we want
the loop to execute. (T!)
• It is commonly used to process all the elements stored in an array data
structure (coming up in a few weeks!)

INFO 6066
Syntax of the for loop declaration header (T!)
• for(expression1; expression2; expression3)
{
//loop body statement(s) ;
} //end for
• The parentheses ( ) contain the loop declaration header.
• expression1 declares and initializes the the loop control variable or loop counter.
Some texts call this the initialization action. This part of the loop header runs just
once, at the start of the loop.
• expression2 is the loop continuation condition expression. It is re-evaluated after
each iteration of the loop
• expression3 is the loop counter adjustment expression. (Some call it the action-
after-each-iteration). It is the last action done in an iteration of the body code
before the loop goes back to check the LCC again.
• Usually we increment (add to ) the counter, but it is also possible to do a
decrement (subtract from the counter) if we want to do a count-down loop.

INFO 6066
Recap: Unary Operators:
Increment ++ and Decrement --
• ++ :the increment operator is used to add one to a variable
• -- :the decrement operator is used to subtract one from a
variable
• Commonly used to control loop counter variables

example: for(int count = 0; count <5; count++)

• The ++ increments the variable count by 1 after each iteration


of the loop.

INFO 6066
Flow Chart: for Loop
Counter variable initialization

Action after Continuation


false
each iteration
condition?
(increment)

truestatement(s) in Loop
Run
Body

Run next statement

INFO 6066
for Loop Example
• int sum = 0;
for(int counter = 0; counter < 5; counter++)
{
sum = sum + counter;
} //end for
NOTE: if there is only one statement in the loop body the braces can
be omitted, but good coders ALWAYS put them in for clarity.
ALWAYS DO THIS!
• Q. How many times will the loop body execute?
• Q. What is the value of sum after the loop ends?

INFO 6066
Common Error in for Loops
• The most common error when first using for loops is to put a semi-colon
after the closing parentheses of the loop declaration header.
• for(int count = 0; count < 5; count++) ; //semicolon here is error
• This actually separates the loop header from the code in the loop body.
(T!) The two parts then run independently of each other.
• Statements inside the loop body will not be executed as you intended if
you do this. (this is called a logic error)
• Example of an infinite for loop you might see someday…
for ( ; ; ) { }
• NOTE: If the for loop continuation condition is omitted, then Java assumes
that it is implicitly true and will run the loop infinitely unless a break
condition appears in the loop body.

INFO 6066
break Keyword
• Used to break out of a loop if a certain condition is met.
• for (int i = 1; i < 10; i++)
{
if(i % 3 == 0)
break; //exits the loop completely
total += i;
}//end for

…next statement
• here, loop execution ends if i is a multiple of 3, and execution
continues with next statement after the loop.

INFO 6066
continue Keyword
• continue will stop further execution of the current iteration of a loop
• it will then evaluate the loop condition , and if true, will continue loop for
another iteration
• Example: we don’t want to increment the variable named total if loop
control variable “i” is a multiple of 3 ( 3, 6, 9, etc…)
• We’ll use modulus division to see if a value is a multiple of 3. If we do value
% 3 and it returns an answer of zero, then we know that value is a multiple
of 3.

INFO 6066
continue Example
• for (int i = 1; i < 10; i++)
{
if (i % 3 == 0)
{
continue; //if this code runs, total is not incremented
// on this iteration of the loop.
} //end if
total += i;
} // end for
• if “i” is a multiple of 3, then variable total is not incremented on
these iterations. Control goes back to top and checks to see if
the loop continuation condition is still true. If it is, another loop
iteration is done.

INFO 6066
CONTINUE vs BREAK

• Remember: a continue keyword stops only the current iteration of the


loop. (T!)
• Flow of control goes back to the loop condition to see if any more
iterations should be done.
• The break keyword causes control to break out of the loop body
completely, no matter how many iterations might remain.
• Flow of control proceeds to the next statement after the loop structure.

INFO 6066
The (for : each) loop
• The (for : each) loop construct was added to Java in the 1.5 update
to make it easier to process data in storage structures such as
arrays, ArrayLists, and Vectors (coming up in the next unit).
• Basically, it allows you to process all the data values stored in the
storage structure without having to worry about how many
elements there are in the structure ( this saves a few lines of code)
• It uses what is called an iterator (it’s like an indicator that points to
each value in the data structure) to iterate through the values.
• It does have its usefulness, but it is actually a little less powerful
than a standard for loop.

INFO 6066
For each Example
int [] myArray = {16, 24, 96, 26, 34, 76, 27, 24, 88};
//create an alias for your array
for(int mine: myArray)
{
//use the alias to work through the array
System.out.print(mine + "\t");
}

INFO 6066
For each

Pros: Cons:
•Easy to set up. – You cannot change the contents of an
•Never have to be concerned about going off element
the end of the array. – You cannot traverse the elements in
reverse order
– Cannot us if you need to access only
some, not all, of the elements
– Cannot use f you need to access more
than one array or ArrayList at the same
time inside the loop
– Cannot use f you need to refer to the
index number of a particular element.

INFO 6066
Homework – Chapter 4 & 18
4.1 Loops (general)
4.2 While loops
4.3 More while examples
18.1 Do-while loops
4.4 For loops
4.5 More for loop examples
4.6 Loops and strings
4.7 Nested loops
4.8 Developing programs incrementally
4.9 Break and continue
4.10 Variable name scope
4.11 Enumerations
4.12 Java example: Salary calculation with loops
4.13 Java example: Domain name validation with loops

INFO 6066

You might also like