Loops Test Flashcards

(38 cards)

1
Q

What is the increment operator?

A

++

number++;
This statement is like saying number = number + 1 Which is get the current value of number and add 1 to it. Therefore, current value of number is 4, add 1, number is now 5

Can also be written as ++number

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

What is the decrement operator?

A

This statement is like saying number = number - 1 Which is get the current value of number and subtract 1 to it… Therefore, current value of number is 5, subtract 1, number is now 4

Can also be written as –number

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

What is a loop?

A

A loop is a part of a program is repeated over and over, until a specific goal
is reached. Loops are important for calculations that require repeated steps
and for processing input consisting of many data items.

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

What is the while loop?

A

The while loop has two
important parts: (1) do a boolean expression that is tested for a true or false
value, and (2) a statement or block of statements that is repeated as long as the
expression is true. In a loop, we need to have something that will tell it when to
stop iterating (stop looping).

While loop is a pretest loop – test it before we do any iteration – false(no iterations done) and true(will perform at least one iteration)

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

What is an iteration?

A

An iteration is when the loop has executed its block of code once.

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

What is a control varaible?

A

A control variable is used to “keep track” of how many times a loop
has iterated. Without a control variable, a loop will not have any indication when
to stop. This can result in an infinite loop.

You need to increment the control variable or else an infinite loop will happen – will run until the control variable makes the boolean false and then the loop will stop running – the boolean expression controls the condition which the control variable must follow

Control variable can be initialized as any number – most of the time it’s one

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

What is happening in this code?

int number = 1;

  while (number <= 5)
  {
     System.out.println("Hello");
     // Print "Hello"

     number++;
     // Add 1 to the current value of number.
     // Removing this line will cause an infinite loop
  }
   
  System.out.println("That's all!");    } }
A

This while loop tests the variable “number” to determine whether it is less than or equal to 5. if true, it will run its block of code. At the end of the block, it will test the expression again.

The expression will result in true once more because the value of number will be 2, and 2 is less than 5 therefore true, so run the block again… It will continue with this process until the expression is false. At some point number will not be less than or equal to 5, at that point, the loop will no longer run and the program will continue with whatever code comes after. Each time a loop runs its block of code, we call that an “iteration”. In this case, this loop will have iterated 5 times.

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

What is input validation demonstrated with?

A

Input validation is demonstrated with while loops.

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

What is the do-while loop?

A

The do-while loop is a post-test loop. This means it does not test its boolean expression until it has completed an iteration. As a result, the do-while loop always performs at least one iteration, even if the boolean expression is false to begin with. You should use the do-while loop when you want to make sure the loop executes at least once

Do while loop - posttest - will iterate any least once whether it’s true or false – after if iteration it will test it (tests it after each iterations)
Example: taking the average of three test scores and asking if the user wants to input new scores and calculate their average again – we want to ask the question AFTER the iteration so it makes more sense to use a do while loop

The do while loop will iterate at least once regardless of the expression and if its false because it is a posttest loop

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

What is the for loop?

A

The for loop is ideal for performing a known number of iterations.

A count-controlled loop must possess three elements:
1. It must initialize a “control variable” to a starting value.
2. It must test the control variable by comparing it to a maximum value. When the control variable reaches its maximum value, the loop terminates.
3. It must update the control variable during each iteration. This is usually done by incrementing the variable.

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

Explain this: for(numberOne = 1; numberOne <= 10; numberOne++)

A

The first line of the for loop is known as the “loop header”. After the key word for, there are three expressions inside the parentheses, separated by semicolons. (Notice there is not a semicolon after the third expression.)

The first expression is the “initialization expression”. It is normally used to initialize a control variable to its starting value. This is the first action performed by the loop, and it is done only once.

The second expression is the “Test Expression”. This is a boolean expression that controls the execution of the loop. As long as this expression is true, the body of the for loop will repeat. The for loop is a “pretest-loop”, so it evaluates the test expression before each iteration.

The third expression is the “update expression”. It executes at the end of each iteration. Typically, this is a statement that increments the loop’s control variable.

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

How do you add 2 to the counter for a for loop?

A

for (int numberTwo = 2; numberTwo <= 100; numberTwo += 2)

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

How to determine the maximum value of the control varaible?

A

Sometimes you want the user to determine the maximum value of the control variable in a for loop, and therefore determine the number of times the loop iterates. Instead of displaying the numbers 1 through 10 and their squares, this program allows the user to enter the maximum value to display. This program demonstrates a user controlled for loop.

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

How do you use multiple ststament in a for loop?

A

It is possible to execute more than one statement in the initialization expression and the update expression. When using multiple statements in either of these expressions, simply separate the statements with commas.

for (a = 1, b = 1; a <= 5; a++)
// This for loop has two control variables named “a” and “b”
{
System.out.println(a + “ plus “ + b + “ equals “ + (a + b));

int c, d;
// This line declares two integer variables named “c” and “d”

           for (c = 1, d = 1; c <= 5; c++, d++)
           // This loop has two control variables that are updated with every iteration
           {
            System.out.println(c + " plus " + d + " equals " + (c + d));
           }

        }

Connecting multiple statements with commas works well in the initialization and update expressions, but don’t try to connect multiple boolean expressions this way in the test expression. If you wish to combine multiple boolean expressions in the test expression, you must use the && or || operators.

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

What 2 elements do programs use to calculate the total of a series of numbers?

A

Programs that calculate the total of a series of numbers typically use two elements:

  1. A loop that reads each number in the series.
  2. A variable that accumulates the total of the numbers as they are read.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is an accumulator?

A

The variable used to accumulate the total of the numbers is called an “accumulator”. It is often said that the loop keeps a running total because it accumulates the total as it reads each number in the series.

totalSales = 0.0;

This line assigns 0.0 to the totalSales variable. In general programming terms, the totalSales variable is referred to as an accumulator. An accumulator is a variable that is initialized with a starting value, which is usually zero, and then accumulates a sum of numbers by having the numbers added to it.

Accumulative variable – adds input each iteration – you need to initialize this variable at the beginning of the code to zero (when you put variable += value and you don’t make it assigned to a value it won’t know the current value to accumulate)

17
Q

What is sentinel value and when it is used?

A

The program in the previous example requires the user to know in advance the number of days for which he or she has sales figures.

Sometimes the user has a very long list of input values, and doesn’t know the exact number of items. In other cases, the user might be entering values from several lists and it is impractical to require that every item in every list is counted. A technique that can be used in these situations is to ask the user to enter a “sentinel value” at the end of the list.

A sentinel value is a special value that cannot be mistaken as a member of the list, and it signals that there are no more values to be entered. When the user enters the sentinel value, the loop terminates.

The value -1 was chosen for the sentinel because it is not possible for a team to score negative points.

Notice that this program performs a priming read to get the first value. This makes it possible for the loop to terminate immediately if the user enters -1 as the first value. Also note that the “sentinel value” is not included in the running total.

Sentinel value – a value that cannot be a part of the data set and signals to the program the end of a data set (like a flag variable)
Signals there is no more values to be entered

18
Q

What is a PostFix operator?

A

PostFix example
The output is 4 – because numberOne++ is a postfix operator (does the operation after the variable), meaning that it will print the argument THEN add one – numberONe is assigned five now but it isn’t displayed

19
Q

What is this code:
int x = 5;
int y = ++x + x–;

A

Adds one to x = 5 (6), then add 6 (12), 12 is assigned to y – subtract one to make it eleven HOWEVER y is still 12 because y is already assigned – prints 12
int y = ++x + –x;
Add one to x and becomes 6, subtract one from 6 (5), then it becomes 6 + 5
int z = x++ + x–;
Adds x to x (10), adds ones (11), assigns 11 to z and subtract 1 (but this is pointless because z is already assigned 11

20
Q

What is happening in this code?
final double MAX_TEMP = 102.5;
double temperature;
Scanner input = new Scanner(System.in);

System.out.print(“Enter the substance’s temperature in celsius temperature: “);
temperature = input.nextDouble();

while(temperature > MAX_TEMP)
{
System.out.println(“The temperature is too high. Turn the”);
System.out.println(“thermostat down and wait 5 minutes”);
System.out.println(“Then, take the celsius temperature again”);
System.out.print(“and enter it here: “);
temperature = input.nextDouble();
}
System.out.println(“The temperature is acceptable.”);
System.out.println(“Check it again in 15 minutes.”);
input.close();

A

Make the temperature variable a named constant – the coder knows that temperature must not change – named in all caps
The code repeats when the temperature is not the right value – no incrementing control variables needed because loop is based on a condition (we don’t know how long it will need to iterate for)
In the block of statements – we want to repeat an error message and get the user to reinput a temperature (prompt user and parse it every time )

21
Q

What are the steps for a while loop?

A

Steps:
1. Initialize a control variable to any number (here, 1).
2. Set up a while loop that assigns a condition to the control variable (here, less than or equal to 5).
3. Inside the loop, print “Hello”.
4. Increment the control variable by 1 after each iteration. (How many tries it can use until reaches 5 (increases by 1 each time))
5. After the loop ends, print “That’s all”.

22
Q

What occurs with increment and decrement between prefix and postfix?

A

int number = 2; – int x = number++ – assigns 2 BEFORE it adds the one

Increment/decrement in the print statement with a postfix, post fix outside a print statement == VALUE STAYS THE SAME

Increment/decrement in the print statement with a prefix, prefix outside a print statement == VALUE INCREMENTS OR DECREMENTS

*** postfix – value stays the same and prefix – value changes EVEN in a combination of the two

23
Q

What do loops do?

A

Three things: checking the condition, keeping track of iterations and updating the control variable

24
Q

What is within a for loop?

A

Initialization expression for control variable, test expression to test the control variable, the update expression which updates the control variable all in one header

25
What is the difference between the while and for loop?
The difference between the while and for loop: if you don’t know the amount of times you will iterate then use a while loop because its dependent on user input and a for loop is used when you know the exact amount of times use want the loop to iterate
26
What is a local vs global varaible?
Local variable (if the control variable is initialized inside the for loop) and global variable (assigned outside of loop and can be used throughout the program)
27
What occurs in this code? System.out.println("println first: " + numberOne++);
This is PostFix int numberOne = 4; System.out.println("\nPostfix Example:"); System.out.println("println first: " + numberOne++) This statement will first print the current value of numberOne then it will add 1 to it. Therefore it will print 4, numberOne will have a value of 5 after it has printed the current value. System.out.println("After println: " + numberOne); // This statement will print 5
28
What happens in this code? System.out.println("println first: " + ++numberTwo);
Prefix example int numberTwo = 4; System.out.println("\nPrefix Example:"); System.out.println("println first: " + ++numberTwo); This statement will first add 1 to the current value of numberTwo then it will print numberTwo. Therefore it will print 5 System.out.println("After println: " + numberTwo); // This statement will print 5
29
What are a few points about nested loops?
1. An inner loop goes through all of its iterations for each iteration of an outer loop. 2. Inner loops complete their iterations before outer loops do. 3. To get the total number of iterations of a nested loop, multiply the number of iterations of all the loops.
30
What is the break statement?
The break statement, which was used with the switch statement in "Decision Structures", can also be placed inside a loop. When it is encountered, the loop stops and the program jumps to the statement immediately following the loop. Although it is perfectly acceptable to use the break statement in a switch statement, it is considered taboo to use it in a loop. This is because it bypasses the normal condition that is required to terminate the loop, and it makes the code difficult to understand and debug. For this reason, you should avoid using the break statement in a loop when possible
31
What is teh continue statement?
The continue statement causes the current iteration of a loop to end immediately. When continue is encountered, all the statements in the body of the loop that appear after it are ignored, and the loop prepares for the next iteration. In a while loop, this means the program jumps to the boolean expression at the top of the loop. As usual, if the expression is still true, the next iteration begins. In a do-while loop, the program jumps to the boolean expression at the bottom of the loop, which determines whether the next iteration will begin. In a for loop, continue causes the update expression to be executed, and then the test expression is evaluated. The continue statement should also be avoided. Like the break statement, it bypasses the loops logic and makes the code difficult to understand and debug.
32
What is the best situation to use the while loop?
The while loop. The while loop is a pretest loop. It is ideal in situations where you do not want the loop to iterate if the condition is false from the beginning. It is also ideal if you want to use a sentinel value to terminate the loop.
33
What is the best situation to use the do-while loop?
The do-while loop. The do-while loop is a posttest loop. It is ideal in situations where you always want the loop to iterate at least once.
34
What is the best situation to use the for loop?
The for loop. The for loop is a pretest loop that has built-in expressions for initializing, testing, and updating. These expressions make it very convenient to use a loop control variable as a counter. The for loop is ideal in situations where the exact number of iterations is known.
35
How do you generate random numbers?
Random numbers are used in a variety of applications. Java provides the Random class that you can use to generate random numbers. import java.util.Random; // Needed for the Random class Random randomNumbers = new Random(); This line creates a random object named "randomNumbers" from the Random class
36
What does this line generate? number1 = randomNumbers.nextInt(100) + 1;
This line generates a random number between 1 and 100. The nextInt(100) method actually generates a number from 0 to 99, however we want a number between 1 and 100. This is why we add 1 to the method. The variable "number1" will reference the number generated.
37
How do you get a random floating point number?
You can get a random floating point number by changing the Scanner method (ie. nextDouble)
38
What does this statement print? number1 = randomNumber.nextInt(10) + 1;
If you don’t specify a value -- generates the range of an int (two billion possibilities)