LOOPS
6.1-6.2
LOOP
• A loop is a line of code that will tell the computer to
repeat a block of code until a condition is met. There are
several types of loops.
WHILE LOOP
• With a while loop, the computer will check a boolean
condition. If the condition is true it will run the included
code.
• At the end of the block of code, it will check the condition
again. If the condition is true, it will repeat the code and
check again.
• Continues while the condition is true
INFINITE LOOPS
• Be sure that your condition will become false at some point
otherwise the loop and the program never ends. This is
called an infinite loop and can be a difficult logic error to
correct at times.
SYNTAX
while (boolean condition)
{
code to be run…
}
SCOPE OF A VARIABLE
• Remember any variable that you create only exists within
the block of code in which it is created.
• If you create a variable in a while loop, when it gets to
the end of the block of code it is discarded. In the next
iteration a new variable is created.
SCOPE
int x = 0;
while (x<10)
{
int y = 0;
y++;
x++;
}
System.out.print(“x = “ + x + “, y = “ + y);
WRITE A METHOD WHICH TAKES PARAMETERS FOR
BALANCE AND INTEREST AND RETURNS AN INTEGER FOR
HOW LONG IT TAKES TO TRIPLE THE INVESTMENT.
public int tripleTime(double bal, double rate)
{
}
WRITE TWO PROGRAMS
• Write a program using the Dice class which will create two dice objects
and repeatedly roll until you get doubles. Display the value of each
roll and their sum, and display the total number of rolls it took before
getting doubles.
• Write a program which creates two Dice objects.
Prompts the user for a
target value between 2 and 12. Make sure that the target value is
valid. If it is not, prompt the user again. Roll the two dice until the
target is rolled. Display each roll and their sum, and display the total
number of rolls before the target was reached.
• Print both to be turned in tomorrow.
© Copyright 2026 Paperzz