Loops Flashcards

1
Q

Loop

A

A control structure that causes a statement or group of statements to repeat.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Three types of loops in Java

A
  1. While loop
  2. For loop
  3. Do-while loop
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

While loop

A

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++;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Do-while loop

A

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.”);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

For loop

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you decide which loop to use?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Accumulator

A

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
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Loop control variable

A

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!”);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Counter

A

A variable that is initialized with 0 and incremented whenever there is a match. Often times a counter is also a loop control variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Increment and decrement operators

A

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;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Sentinel

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Infinite loop

A

A loop that runs forever and can only be stopped by killing the program or restarting the computer. Common reasons for infinite loops are:

  1. 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;
    }
  2. 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–;
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Off-by-one errors

A

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:

  1. Initializing a counter to the wrong value such as 0 instead of 1 or vice versa
  2. Using the wrong relational operator such as < instead of <= or vice versa
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Symmetric bounds

A

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++)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Asymmetric bounds

A

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++)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Nested loop

A

A loop that is contained in another loop. We refer to the inner loop as a nested inside the outer loop.

A typical use of nested loops is printing rows and columns. Similarly, when processing tables, nested loops occur naturally. An outer loop iterates over all rows of the table and an inner loop iterates over all columns in the current row.

17
Q

Loop and a half

A

A loop whose true test to decide termination is neither at the beginning nor at the end, but in the middle. That is, one must go halfway into the loop before knowing whether or not to terminate.

For example:
boolean done = false;

while (!done)
{
String input = in.next();
if (input.equals(“Q”)
{
done = true;
}
else
{
Statement;
}
}

18
Q

Redirection

A

Linking the input or output of a program to a file instead of the keyboard or display.

19
Q

Hand tracing

A

A simulation of code execution in which you step through instructions and track the values of variables. This helps you understand how unfamiliar algorithms work and can expose errors in code of pseudocode.

20
Q

What are the steps to write a loop?

A
  1. Decide what work must be done inside the loop. The key here is to identify the repeative task, such as updating a variable (i.e. bank balance or total) or incrementing a counter. If you’re having trouble doing this, then write down the steps that you’d take to solve the problem by hand and reduce them to a set of uniform actions that can be placed into the loop body.
  2. Specify the loop condition or goal that you want to reach with the loop. Typical examples are:
    • Has a counter reached its final value?
    • Have you read the last input value?
    • Has a value reached a given threshold?
  3. Determine the loop type. The general rule of thumb is to use a for loop if there’s a definite number of iterations. Otherwise, use a while loop.
  4. Set up variables for entering the loop for the first time. This includes all variables that are used and updated in the loop. Commonly, counters are initialized with 0 or 1 and totals are initialized with 0.
  5. Implement the loop. Hard trace it running to ensure that it produces the desired results.
21
Q

Common loop algorithms: Summing values

A

To sum values you keep a running total by creating a variable known as an accumulator, initialized with 0, to which you add each input value:

double total = 0;
while (in.hasNextDouble())
{
double input = in.nextDouble();
total = total + input:
}

22
Q

Common loop algorithms: Calculating an average

A

To compute an average of multiple values, count how many values you have and divide the sum of those values by the count:

double total = 0;
int count = 0;
while (in.hasNextDouble())
{

double input = in.nextDouble();

total = total + input;
count++;
}
double average = 0;

if (count > 0)
{

average = total / count;
}

23
Q

Common loop algorithms: Counting matches

A

To count values that fulfill a condition, check all values and increment a counter for each match. For example, to count the number of spaces in a string:

int spaces = 0;

for (int i = 0; i < str.length(); i++)
{

char ch = str.charAt(i);
if (ch == ‘ ‘)
{

spaces++;
}

}

24
Q

Common loop algorithms: Finding the first match

A

In this case, you do not need to check all values. Instead, you can exit the loop as soon as the condition is met. For example, to find the first space in a string:

boolean found = false;

char ch = ‘?’;

int position = 0;

while (!found && position < str.length( ))
{
char = str.charAt(position);
if (ch == ‘ ‘)
{

found = true;
}

else
{

position++;
}

}

*Note, a while loop is a better choice than a for loop since we do not visit all elements in the string.

25
Q

Common loop algorithms: Input validation

A

You can use a loop to keep asking a user to enter valid input as long as invalid values are provided. For example, if a user is asked to enter a positive number less than 100:

boolean valid = false;

double input = 0;

while (!valid)
{

System.out.print(“Please enter a positive number < 100”);
input = in.NextDouble();

if (0 < input && input < 100)
{

valid = true;

}
else
{

System.out.println(“Invalid input.”);
}
}

26
Q

Common loop algorithms: Finding maximum value

A

To find the largest value in a sequence, keep a variable that stores the largest element that you’ve seen so far and update it anytime a larger value is found. For example:

double max = in.nextDouble;

while (in.hasNextDouble())
{

double input = in.nextDouble();

if (input > max)

{

max = input;

}
}

27
Q

Common loop algorithms: Find minimum value

A

To find the smallest value in a sequence, keep a variable that stores the smallest element that you’ve seen so far and update it anytime a smaller value is found. For example:

double min = in.nextDouble;

while (in.hasNextDouble())
{

double input = in.nextDouble();

if (input < min)

{

min = input;

}
​}

28
Q

Common loop algorithms: Comparing adjacent values

A

When processing a sequence of values in a loop, sometimes you need to compare a value with the value that just preceded it. This is helpful to identify duplicates, for example. To do so, you must store the prior value (which is typically overriden in a loop) like this:

double input = in.nextDouble;
while (in.hasNextDouble())
{

double previous = input;

input = in.nextDouble();

if (input == previous)
{

System.out.println(“Duplicate input.”);
}
}

29
Q

How do you compute the total of all positive inputs?

A

double total = 0; // Accumulator
while (in.hasNextDouble())
{
double input = in.nextDouble();
if (input > 0)
{
total =+ input;
}
}

30
Q

How do you find the position of the last space in a string?

A

Start the loop at the end of the string:
boolean found = false;

int i = str.length() - 1;
while (!found && i >= 0)
{
char ch = str.charAt(i);
if (ch == ‘ ‘)

{

found = true;
}
else
{
i–;
}
}

31
Q

Pseudorandom numbers

A

A number that appears to be random but is generated by a mathematical formula. This is true of numbers generated with the Random class in Java.

32
Q

Write a loop to count the number of vowels in a string

A

String word = “Test String”;
int count = 0;
for (int i = 0; i < word.length(); i++)
{
char ch = word.charAt(i);
if (ch == ‘a’ || ch == ‘A’ ||
ch == ‘e’ || ch == ‘E’ ||
ch == ‘i’ || ch == ‘I’ ||
ch == ‘o’ || ch == ‘O’ ||
ch == ‘u’ || ch == ‘U’)
count++;
}

33
Q

How do you write a loop that starts processing data at the end of a string, as opposed to the beginning?

A

for (int i = str.length() - 1; i >= 0; i–)

System.out.println(str.charAt(i));