CP1 Lab 3 mid Topics: Control Statements
Main topics:
• The Increment and Decrement Operators
• The while Loop
• Using the while Loop for Input Validation
• The do-while Loop
• The for Loop
• Running Totals and Sentinel Values
Note: Java Switch Statements
Instead of writing many if..else statements, you can use the switch
statement.
The switch statement selects one of many code blocks to be executed:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The Increment and Decrement Operators
• There are numerous times where a variable
must simply be incremented or decremented.
number = number + 1;
number = number – 1;
• Java provide shortened ways to increment and
decrement a variable’s value.
• Using the ++ or -- unary operators, this task
can be completed quickly.
number++; or ++number;
number--; or --number;
• Example: IncrementDecrement.java
Differences Between Prefix and Postfix
• When an increment or decrement are the only
operations in a statement, there is no
difference between prefix and postfix
notation.
• When used in an expression:
• prefix notation indicates that the variable will be
incremented or decremented prior to the rest of the
equation being evaluated.
• postfix notation indicates that the variable will be
incremented or decremented after the rest of the
equation has been evaluated.
The while Loop
• Java provides three different looping structures.
• The while loop has the form:
while(condition)
{
statements;
}
• While the condition is true, the statements will
execute repeatedly.
• The while loop is a pretest loop, which means
that it will test the value of the condition prior to
executing the loop.
The while Loop
• Care must be taken to set the condition to false somewhere in
the loop so the loop will end.
• Loops that do not end are called infinite loops.
• A while loop executes 0 or more times. If the condition is
false, the loop will not execute.
• Example: WhileLoop.java
The while loop Flowchart
true
boolean
statement(s)
expression?
false
Infinite Loops
• In order for a while loop to end, the condition
must become false. The following loop will not
end:
int x = 20;
while(x > 0)
{
System.out.println("x is greater than 0");
// x--;
}
• The variable x never gets decremented so it
will always be greater than 0.
• Adding the x-- above fixes the problem.
Infinite Loops
•This version of the loop decrements
x during each iteration:
int x = 20;
while(x > 0)
{
System.out.println("x is greater than 0");
x--;
}
Block Statements in Loops
• Curly braces are required to enclose block statement while
loops. (like block if statements)
while (condition)
{
statement;
statement;
statement;
}
The while Loop for Input Validation
• Input validation is the process of ensuring that
user input is valid.
Sample code:
System.out.print("Enter a number in the " +
"range of 1 through 100: ");
number = keyboard.nextInt();
// Validate the input.
while (number < 1 || number > 100)
{
System.out.println("That number is invalid.");
System.out.print("Enter a number in the " +
"range of 1 through 100: ");
number = keyboard.nextInt();
}
The do-while Loop
• The do-while loop is a post-test loop, which
means it will execute the loop prior to testing
the condition.
• The do-while loop (sometimes called a do
loop) takes the form:
do
{
statement(s);
}
while (condition);
The do-while Loop Flowchart
statement(s)
true
boolean
expression?
false
The for Loop
• The for loop is a pre-test loop.
• The for loop allows the programmer to
initialize a control variable, test a condition,
and modify the control variable all in one line
of code.
• The for loop takes the form:
for(initialization; test; update)
{
statement(s);
}
The for Loop Flowchart
boolean true
statement(s) update
expression?
false
The Sections of The for Loop
• The initialization section of the for loop
allows the loop to initialize its own control
variable.
• The test section of the for statement acts in
the same manner as the condition section of a
while loop.
• The update section of the for loop is the last
thing to execute at the end of each loop.
The for Loop Initialization
• The initialization section of a for loop is
optional; however, it is usually provided.
• Typically, for loops initialize a counter
variable that will be tested by the test section
of the loop and updated by the update
section.
• The initialization section can initialize multiple
variables.
• Variables declared in this section have scope
only for the for loop.
The Update Expression
• The update expression is usually used to
increment or decrement the counter
variable(s) declared in the initialization section
of the for loop.
• The update section of the loop executes last in
the loop.
• The update section may update multiple
variables.
• Each variable updated is executed as if it were
on a line by itself.
Modifying The Control Variable
• You should avoid updating the control variable of a for loop
within the body of the loop.
• The update section should be used to update the control
variable.
• Updating the control variable in the for loop body leads to
hard to maintain code and difficult debugging.
Multiple Initializations and Updates
• The for loop may initialize and update multiple
variables.
for(int i = 5, int j = 0; i < 10 || j < 20; i++, j+=2)
{
statement(s);
}
• Note that the only parts of a for loop that are
mandatory are the semicolons.
for(;;)
{
statement(s);
} // infinite loop
• If left out, the test section defaults to true.
Running Totals
• Loops allow the program to keep running totals while evaluating
data.
• Imagine needing to keep a running total of user input.
Logic for Calculating a Running Total
Sentinel Values
• Sometimes the end point of input data is not known.
• A sentinel value can be used to notify the program to
stop acquiring input.
• If it is a user input, the user could be prompted to input
data that is not normally in the input data range (i.e. –1
where normal input would be positive.)
• Programs that get file input typically use the end-of-file
marker to stop acquiring input data.
Nested Loops
• Like if statements, loops can be nested.
• If a loop is nested, the inner loop will execute
all of its iterations for each time the outer loop
executes once.
for(int i = 0; i < 10; i++)
for(int j = 0; j < 10; j++)
loop statements;
• The loop statements in this example will
execute 100 times.
The break Statement
• The break statement can be used to abnormally terminate a
loop.
• The use of the break statement in loops bypasses the normal
mechanisms and makes the code hard to read and maintain.
• It is considered bad form to use the break statement in this
manner.
The continue Statement
• The continue statement will cause the
currently executing iteration of a loop to
terminate and the next iteration will begin.
• The continue statement will cause the
evaluation of the condition in while and for
loops.
• Like the break statement, the continue
statement should be avoided because it
makes the code hard to read and debug.
Deciding Which Loops to Use
• The while loop:
• Pretest loop
• Use it where you do not want the statements to
execute if the condition is false in the beginning.
• The do-while loop:
• Post-test loop
• Use it where you want the statements to
execute at least one time.
• The for loop:
• Pretest loop
• Use it where there is some type of counting
variable that can be evaluated.
Activity: Run and
Debug the code
samples
Quiz 1 Lab Mid
Activity:
Sample Code:
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
public class Main {
public static void main(String[] args) {
String[] cars = {“Mazda", “Mitsubishi",
“Toyota", “Zapra"};
for (String i : cars) {
System.out.println(i);
}
}
}
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
}
}
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
}
}
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
public class Main {
public static void main(String[] args) {
String[] cars = {"Mazda", "Toyota", "Mitsubishi",
"Honda"};
for (String i : cars) {
System.out.println(i);
}
}
}
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
}
}
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
}
}