What is the increment operator?
++
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
What is the decrement operator?
–
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
What is a loop?
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.
What is the while loop?
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)
What is an iteration?
An iteration is when the loop has executed its block of code once.
What is a control varaible?
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
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!"); } }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.
What is input validation demonstrated with?
Input validation is demonstrated with while loops.
What is the do-while loop?
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
What is the for loop?
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.
Explain this: for(numberOne = 1; numberOne <= 10; numberOne++)
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 do you add 2 to the counter for a for loop?
for (int numberTwo = 2; numberTwo <= 100; numberTwo += 2)
How to determine the maximum value of the control varaible?
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 do you use multiple ststament in a for loop?
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.
What 2 elements do programs use to calculate the total of a series of numbers?
Programs that calculate the total of a series of numbers typically use two elements:
What is an accumulator?
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)
What is sentinel value and when it is used?
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
What is a PostFix operator?
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
What is this code:
int x = 5;
int y = ++x + x–;
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
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();
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 )
What are the steps for a while loop?
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”.
What occurs with increment and decrement between prefix and postfix?
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
What do loops do?
Three things: checking the condition, keeping track of iterations and updating the control variable
What is within a for loop?
Initialization expression for control variable, test expression to test the control variable, the update expression which updates the control variable all in one header