Loops Flashcards
Loop
A control structure that causes a statement or group of statements to repeat.
Three types of loops in Java
- While loop
- For loop
- Do-while loop
While loop
A way of repeating a block of code “while” some condition applies, or until some condition is satisfied. While loops are the best option when you don’t know how many times the code will run, such as when a user is inputting data.
While loops are known as pretest loops, which means that they test the boolean expression before each iteration. They’re also known as event-controlled loops or conditional loops, since the number of iterations is not known in advance and it is executed until event happens or some condition is met.
The while loop has two main parts: (1) a boolean expression that is tested for true or false, and (2) a statement or block of statements that is repeated as long as the expression is true.
The general format of a while loop is as follows:
while (boolean expression)
Statement;
For example:
while (number <= 5)
{
System.out.println(“Hello!”);
number++;
}
Do-while loop
A post-test loop. This means that it does not test its boolean condition until it has completed an iteration of the loop. These are ideal to use when you need to execute the loop at least once before it can be terminated.
The general format of a do-while loop is as follows:
do
{
Statement;
Statement;
}
while (boolean expression)
For example:
int value;
do
{
System.out.print(“Enter a number < 100: “);
value = in.nextInt();
}
while (value >= 100);
{
System.out.println(“Please enter a valid number.”);
}
For loop
Another way of repeating a block of code in which a control variable is initialized and incremented by a certain amount for a specified number of times. You can use while loops and for loops to do the same thing, but the general rule of thumb is that if you know that your loop is going to run a definite number of times, use a for loop.
For loops are known as count-controlled loops since they repeat a specific number of times. For that reason, another commonly used terms for a count-controlled loop is definite.
The general format of a for loop is as follows:
for (Initialization expression; Test expression; Update expression)
{
Statement;
Statement;
}
where:
Initialization expression = used to initialize a control variable to its starting value
Test expression = a boolean expression that controls the execution of the loop
Update expression = executes at the end of each iteration to typically increment or decrement the loop control variable
For example, the following for loop is used to read twelve temperature values (one for each month of the year) and return the month with the highest temperature:
double highestTemp;
highestTemp = in.nextDouble();
int hottestMonth = 1;
for (int currentMonth = 2; currentMonth <= 12; currentMonth++)
{
double nextValue = in.nextDouble();
if (nextValue > highestTemp)
{
highestTemp = nextValue;
hottestMonth = currentMonth;
}
}
System.out.println(hottestMonth);
How do you decide which loop to use?
If you know that your loop will run a finite number of times, then choose a for loop. That is count-controlled loops can be implemented as for loops. Otherwise, use a while loop unless you need to complete one iteration of the loop before you can tell when to terminate the loop in which case use a do-while loop.
Accumulator
A variable that you use to keep a running total as a loop executes. For example, in the following code, totalSales is an accumulator:
for (int count = 1; count <= days; count++)
{
sales = in.nextInt();
totalSales += sales; // adds sales to totalSales
}
Loop control variable
A variable that controls the number of times that a loop repeats or iterates.
For example, in the following loop, the number is a loop control variable:
while (number <= 5)
{
System.out.println(“Hello!”);
}
Counter
A variable that is initialized with 0 and incremented whenever there is a match. Often times a counter is also a loop control variable.
Increment and decrement operators
Operators that add, ++, and subtract, –, one from their operands. For example:
number++;
number–;
*Note that this can be written in postfix mode (as shown above) or in prefix above (as shown below) although the latter much less common.
++number;
–number;
Sentinel
A special value that is not an actual input (i.e. value to be used in the program) but serves as a signal for termination. For example, whenever you’re reading a sequence of inputs you need to have some method of indicating the end of the sequence. Sometimes you’re lucky and no input value be zero. In this case you prompt the user to keep entering numbers or 0 to escape. However, if zero is a valid input, but negative numbers are not allowed, then you could use -1 to indicate termination.
The following loop processes user input until the sentinel is entered:
while (salary != -1)
{
salary = in.nextDouble();
if (salary != -1)
{
sum = sum + salary;
count++;
}
}
*Note that there are two (salary != -1) checks here. The first check ends the loop after the sentinel has been read. The second check ensures that the sentinel is not processed as an input value.
Infinite loop
A loop that runs forever and can only be stopped by killing the program or restarting the computer. Common reasons for infinite loops are:
- Forgetting to update the loop control variable. For example, in the following loop the programmer forgot to add a statement for year++ and as a result, the year is always 1 and the loop never ends:
int year = 1;
while (year <= 20)
{
double interest = balance * RATE / 100;
balance += interest;
} - Accidentally incrementing a counter that should be decremented or vice versa. For example, in the following loop the programmer decremented year instead of incrementing it, so the condition is never satisfied and the loop continues forever:
int year = 1;
while (year <= 20)
{
double interest = balance * RATE / 100;
balance += interest;
year–;
}
Off-by-one errors
A common programming error in which a value is one larger or smaller than it should be. These typically arise due to two common mistakes:
- Initializing a counter to the wrong value such as 0 instead of 1 or vice versa
- Using the wrong relational operator such as < instead of <= or vice versa
Symmetric bounds
Values that are bounded by the relation 1<= i <= 10. For example, when printing all numbers from 1 to 10, you use symmetric bounds:
for (int i =1; 1 <= 10; i++)
Asymmetric bounds
Values that are bound by 0 <= i < str.length()
That is, the starting index value is included, but not the last. This is appropriate here because str.length() is not a valid position.
For example:
for (int = 0; i < str.length(); i++)