0% found this document useful (0 votes)
2 views15 pages

Module 5 - Loops 1

This document provides an overview of Java loops, including while, do-while, and for loops, along with their syntax, semantics, and use cases. It discusses advanced loop concepts such as nested loops, user-controlled loops, and the use of break and continue statements. Additionally, it highlights common errors and pitfalls associated with loop variables and infinite loops.

Uploaded by

net18nt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

Module 5 - Loops 1

This document provides an overview of Java loops, including while, do-while, and for loops, along with their syntax, semantics, and use cases. It discusses advanced loop concepts such as nested loops, user-controlled loops, and the use of break and continue statements. Additionally, it highlights common errors and pitfalls associated with loop variables and infinite loops.

Uploaded by

net18nt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Loops

COP 2250/2210

This presentation contains adapted materials from different sources, including our
designated textbook, to be used for educational purposes only
Summary

• Loops (Repetition or Iteration) • Advance for loops


• The while Loop • Deciding Which Loops to Use
• Summing a List of Numbers • Nested for Loops
• Sentinel value example • The continue and break Statements
• Same Program but User-Controlled Loop • Declaring Loop Variables, Common Errors
• Infinite Loops
• The do-while Loop
• Revisiting the Summation Program
• The for Loop
Loops (Repetition or Iteration)

• We want code to be repeated for many reasons


• to perform a process on multiple sets of data
• to repeat an based on user input or until a particular situation arises
(such as repeating a game until someone wins)
• to perform a computation which requires repeatedly applying the
same operation(s)
• such as computing the first power of 2 greater than 1 million
• to repeat something indefinitely (such as a web server which runs
until we shut it down)

• There are two general forms of loops


• logically controlled
• repeat while (or until) a condition is true, Java has while and do-while
• counter controlled
• repeat a set number of times, Java has the for loop which can repeat a set
number of times based on a starting and ending value or by iterating over a
list
The while Loop

• Consists of two parts


Loop False
• the loop condition and the loop body Continue
Condition?

• Syntax: true
• while(condition)statement; Statement(s)
(loop body)

• Semantics: execute the statement while the


condition is true
Example:
• Whatever variable(s) appear in the condition
need to have values prior to reaching the loop int x = 1;
while(x < 1000000)
x = x * 2;
• If the loop body consists of more than 1
statement then it must be placed in a block {…} This code computes the first power of
• the while Loop can become an infinite loop if the 2 greater than 1 million
loop body does not affect the condition
Summing a List of Numbers
(sentinel value example)
• We want the user to input a list of positive numbers, summing each one to
compute a running total
• We will ask the user to end the list with 0 Example I/O:
Enter any positive number, 0 to quit 10
Enter another positive number, 0 to quit 5
import [Link];
Enter another positive number, 0 to quit 16
public class Summation { Enter another positive number, 0 to quit 3
public static void main(String[] args) { Enter another positive number, 0 to quit 0
Scanner in = new Scanner([Link]); The sum is 34
int sum = 0, value;
[Link]("Enter a number:");
value = [Link]();
while(value > 0) { Sentinel value is 0
sum+=value;
[Link]("Enter a number:");
value = [Link]();
}
[Link]("The sum is " + sum);
}
}
Sentinel loop: When we don't know exactly know how many times the loop body will be
executed
Same Program but User-Controlled Loop
import [Link];

public class Summation {


public static void main(String[] args) {
Scanner in = new Scanner([Link]);
int sum = 0, value;
char user;
String myinput;
[Link]("Do you have a values to sum up? ");
myinput= [Link]().toLowerCase(); Notice that we ask
user=[Link](0);
while(user=='y') { the user for their
[Link]("Enter a number "); value inside the loop
value = [Link]();
sum+=value;
[Link]("Do you have another value to enter? ");
myinput= [Link]().toLowerCase();
user=[Link](0);
}
[Link]("The sum is " + sum);
}
}
User-controlled loop: similar to the sentinel but after each loop iteration, we ask the user
explicitly if they want to continue again or not (yes/no)
Infinite Loops

• In order for a while loop to end, the condition


must become false. The following loop will not end:
int x = 20;
while(x > 0)
{
[Link]("x is greater than 0");
}

• The variable x never gets decremented so it will


always be greater than 0.
• Adding the x--; above fixes the problem.
The do-while Loop
Statement(s)
(loop body)
• The while loop is a pretest loop
• test the condition before entering the loop body
• if the condition is initially false, the loop body never
executes true Loop
• there are situations where you want to do the loop body Continue
Condition?
at least one time
• The do-while loop is a posttest loop False

do
{
statement(s);
}while (condition);

• because of the { }, we can have more than one instruction


• the condition is placed in ( ) as usual but this ends with a ;
which is not usually the case
• semantics: execute the loop body then test the condition
and repeat
• In essence, the do-while is like having a while loop
with the loop body repeated prior to the loop as well
Revisiting the Summation Program

• We can shorten the earlier Summation program by


switching to a do-while loop
• notice how we have to include an if-statement in the loop to
decide whether to add the newest value to sum
import [Link];

public class Summation {


public static void main(String[] args) {
Scanner in = new Scanner([Link]);
int sum = 0, value;
do {
[Link]("Enter a number, 0 to exit ");
value = [Link]();
if(value!=0) sum+=value;
} while(value!=0);
[Link]("The sum is " + sum);
}
}
The for Loop Initial-Action

for(init; condition; increment)


Loop False
statement; Continue
Condition?
• semantics: perform init of whatever variable, test the
true
condition and if true do the statement and perform the
increment operation Statement(s)
(loop body)
• as with the while loop, the loop body is expected to be 1
statement or else must be placed in { } Action After Each
Iteration
• Example:

for (int x = 2; x <= 4; x++)


[Link]("Value of x:" + x);
1. Test the condition
2. If it is false, terminate
3. If it is true, execute the increment statement (except for first round) and then the
body statements
Advance for loops
• Java for loop's three pieces of code (init, condition, incr) can
contain more than one part or be omitted entirely

for(;userAnswer=='y';answer=[Link]().charAt(0)) {…}
• initialization omitted

for(i=0,j=n; i<10 && j<100; i++, j+=i) {…}


• two variables, both initialized, both tested, both incremented

for(i=0; j<n; i++, j+=i) {…}


• two variables but i is initialized even though j is tested
With a complex enough set of for(i=1,sum=0; i<n; i++, sum+=i);
initializations/conditions/increments, we don't
Computes the sum of 1 to n,
even need a loop body – see example to the storing the result in sum
right
Deciding Which Loops to Use

• The while loop:


• Pretest loop
• Use it where you do not want the statements to execute if the
condition is false in the beginning

• The do-while loop:


• Post-test loop
• Use it where you want the statements to execute at least one
time

• The for loop:


• Pretest loop
• Use it where there is some type of counting variable that can be
evaluated
The continue and break Statements
• You might use these if you were in a loop and based on a specific condition, you
did not want the loop to continue
• with break, the loop would exit
• with continue, the rest of the loop body would be skipped and control returns back
at the condition at the top of the loop

int datum = [Link](), sum = 0, count = 0;


while(datum >= 0) {
sum+=datum;
if(sum>100) break;
datum = [Link]();
count++; Assume you want to leave the loop once sum > 100,
} here the break statement permits this

You should avoid using break Notice that the break is not needed, we could accomplish
or continue, they promote poor this task with better logic: change the while loop
logic and lazy programming condition to (datum >= 0 && sum <= 0) and change
the if statement to be if(sum<=100) {datum = …; count++;}
Nested for Loops
• There are times when we need to repeat a set of code a given number
of times but then repeat that a given number of times
• Consider producing a multiplication table
• we need to print out a 2-D grid of values i*j where i is the row and j is the
column
• a single for loop would only control one of these two variables
• two for loops sequentially would control i from start to end and then j from
start to end
• we need to restart j each time i is incremented
• we need 2 nested for loops

int n=4, m=5;


for(int i=1;i<=n;i++) { 1 2 3 4 5
for(int j=1;j<=m;j++) 2 4 6 8 10
3 6 9 12 15
[Link](i*j + "\t");
4 8 12 16 20
[Link]();
}
Declaring Loop Variables, Common Errors, Pitfalls
• We can declare our loop variable(s) inside the for loop itself
• for(int i=0; i<n; i++) …
• i is only valid in the loop body in this case
• if we declared i prior to the for loop, i would be available after the for loop as well
• this can lead to syntax errors if you declare the loop variable in the for statement
and then try to use it after the loop – if in doubt, declare the variable prior to the
loop
• declaring your loop variable both before the loop and in the loop is a syntax
error!

• Infinite loops are easy to create


• remember to look at the loop condition and make sure it can change from
true to false somehow in the loop body
• don't forget that { } are needed for loop bodies of more than 1 instruction –
forgetting them is another way to cause infinite loops

• Remember when testing floating point values that there may be a


slight precision error
• for(double x = 0; x! = n ; x = x + .05)
• this may be an infinite loop because x may never be equal to n exactly

You might also like