Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Java Control Statements: Simple, Compound, and Control - Prof. Jennifer E. Walter, Study notes of Computer Science

Java control statements, including simple statements, compound statements, and control statements. It also provides examples of the repeat-n-times and repeat-until-sentinel idioms, and discusses the switch statement. Java code examples for adding integers using different control patterns.

Typology: Study notes

Pre 2010

Uploaded on 08/19/2009

koofers-user-51j
koofers-user-51j 🇺🇸

10 documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Chapter 4Statement Forms
The Art and Science of
An Introduction
to Computer Science
ERIC S. ROBERTS
Java
Statement Forms
C H A P T E R 4
The statements was interesting but tough.
—Mark Twain, The Adventures of Huckleberry Finn, 1884
CMPU-101
Computer Science I:
Problem-Solving and Abstraction
Fall 2008
Jennifer Walter
(adapted from slides by Eric Roberts)
Statement Types in Java
Programs in Java consist of a set of classes. Those classes
contain methods, and each of those methods consists of a
sequence of statements.
Statements in Java fall into three basic types:
Simple statements
Compound statements
Control statements
Simple statements are formed by adding a semicolon to the
end of a Java expression.
Compound statements (also called blocks) consist of a
sequence of statements enclosed in curly braces.
Control statements fall into two categories:
Conditional statements that specify some kind of test
Iterative statements that specify repetition
Control Statements and Problem Solving
Before looking at the individual control statement forms in
detail, it helps to look more holistically at a couple of
programs that make use of common control patterns.
The next few slides extend the Add2Integers program from
Chapter 2 to create programs that add longer lists of integers.
These slides illustrate three different strategies:
Adding new code to process each input value
Repeating the input cycle a predetermined number of times
Repeating the input cycle until the user enters a special sentinel value
The Add4Integers Program
public class Add4Integers extends ConsoleProgram {
public void run() {
println("This program adds four numbers.");
int n1 = readInt("Enter n1: ");
int n2 = readInt("Enter n2: ");
int n3 = readInt("Enter n3: ");
int n4 = readInt("Enter n4: ");
int total = n1 + n2 + n3 + n4;
println("The total is " + total + ".");
}
}
If you don’t have access to control statements, the only way
you can increase the number of input values is to add a new
statement for each one, as in the following example:
This strategy, however, is difficult to generalize and would
clearly be cumbersome if you needed to add 100 values.
The Repeat-N-Times Idiom
One strategy for generalizing the addition program is to use the
Repeat-N-Times idiom, which executes a set of statements a
specified number of times. The general form of the idiom is
for (int i = 0; i < repetitions; i++) {
statements to be repeated
}
As is true for all idiomatic patterns in this book, the italicized
words indicate the parts of the pattern you need to change for
each application. To use this pattern, for example, you need to
replace repetitions with an expression giving the number of
repetitions and include the statements to be repeated inside the
curly braces.
The information about the number of repetitions is specified by
the first line in the pattern, which is called the header line.
The statements to be repeated are called the body of the for
statement and are indented with respect to the header line.
A control statement that repeats a section of code is called a loop.
Each execution of the body of a loop is called a cycle.
for (int i = 0; i < repetitions; i++) {
statements to be repeated
}
The AddNIntegers Program
public class AddNIntegers extends ConsoleProgram {
public void run() {
println("This program adds " + N + " numbers.");
int total = 0;
for (int i = 0; i < N; i++) {
int value = readInt(" ? ");
total += value;
}
println("The total is " + total + ".");
}
private static final int N = 100;
}
This program uses the Repeat-N-Times idiom to compute the
sum of a predetermined number of integer values, specified by
the named constant N.
The for loop in this example works correctly only if the variable
total is initialized to 0 before executing the loop.
This body of the loop consists of two statements. The first reads
an integer from the user into the variable value, and the second
adds that value to the variable total.
This program uses the Repeat-N-Times idiom to compute the
sum of a predetermined number of integer values, specified by
the named constant N.
public class AddNIntegers extends ConsoleProgram {
public void run() {
println("This program adds " + N + " numbers.");
int total = 0;
for (int i = 0; i < N; i++) {
int value = readInt(" ? ");
total += value;
}
println("The total is " + total + ".");
}
private static final int N = 100;
}
pf3
pf4
pf5

Partial preview of the text

Download Java Control Statements: Simple, Compound, and Control - Prof. Jennifer E. Walter and more Study notes Computer Science in PDF only on Docsity!

Chapter 4—Statement Forms

The Art and Science of

An Introduction

to Computer Science ERIC S. ROBERTS

Java

Statement Forms

C H A P T E R 4

The statements was interesting but tough.

—Mark Twain, The Adventures of Huckleberry Finn, 1884

CMPU-

Computer Science I:

Problem-Solving and Abstraction

Fall 2008

Jennifer Walter

(adapted from slides by Eric Roberts)

Statement Types in Java

• Programs in Java consist of a set of classes. Those classes

contain methods , and each of those methods consists of a

sequence of statements.

• Statements in Java fall into three basic types:

  • Simple statements
  • Compound statements
  • Control statements

• S imple statements are formed by adding a semicolon to the

end of a Java expression.

• C ompound statements (also called blocks ) consist of a

sequence of statements enclosed in curly braces.

• Control statements fall into two categories:

  • Conditional statements that specify some kind of test
  • Iterative statements that specify repetition

Control Statements and Problem Solving

• Before looking at the individual control statement forms in

detail, it helps to look more holistically at a couple of

programs that make use of common control patterns.

• The next few slides extend the Add2Integers program from

Chapter 2 to create programs that add longer lists of integers.

These slides illustrate three different strategies:

  • Adding new code to process each input value
  • Repeating the input cycle a predetermined number of times
  • Repeating the input cycle until the user enters a special sentinel value

The Add4Integers Program

public class Add4Integers extends ConsoleProgram {

public void run() {

println("This program adds four numbers.");

int n1 = readInt("Enter n1: ");

int n2 = readInt("Enter n2: ");

int n3 = readInt("Enter n3: ");

int n4 = readInt("Enter n4: ");

int total = n1 + n2 + n3 + n4;

println("The total is " + total + ".");

• If you don’t have access to control statements, the only way

you can increase the number of input values is to add a new

statement for each one, as in the following example:

• This strategy, however, is difficult to generalize and would

clearly be cumbersome if you needed to add 100 values.

The Repeat-N-Times Idiom

One strategy for generalizing the addition program is to use the

Repeat-N-Times idiom, which executes a set of statements a

specified number of times. The general form of the idiom is

for (int i = 0; i < repetitions ; i++) {

statements to be repeated

As is true for all idiomatic patterns in this book, the italicized

words indicate the parts of the pattern you need to change for

each application. To use this pattern, for example, you need to

replace repetitions with an expression giving the number of

repetitions and include the statements to be repeated inside the

curly braces.

The information about the number of repetitions is specified by

the first line in the pattern, which is called the header line.

The statements to be repeated are called the body of the for

statement and are indented with respect to the header line.

A control statement that repeats a section of code is called a loop.

Each execution of the body of a loop is called a cycle.

for (int i = 0; i < repetitions ; i++) {

statements to be repeated

The AddNIntegers Program

public class AddNIntegers extends ConsoleProgram {

public void run() {

println("This program adds " + N + " numbers.");

int total = 0;

for (int i = 0; i < N; i++) {

int value = readInt("? ");

total += value;

println("The total is " + total + ".");

private static final int N = 100;

This program uses the Repeat-N-Times idiom to compute the

sum of a predetermined number of integer values, specified by

the named constant N.

The for loop in this example works correctly only if the variable

total is initialized to 0 before executing the loop.

This body of the loop consists of two statements. The first reads

an integer from the user into the variable value, and the second

adds that value to the variable total.

This program uses the Repeat-N-Times idiom to compute the

sum of a predetermined number of integer values, specified by

the named constant N.

public class AddNIntegers extends ConsoleProgram {

public void run() {

println("This program adds " + N + " numbers.");

int total = 0;

for (int i = 0; i < N; i++) {

int value = readInt("? ");

total += value;

println("The total is " + total + ".");

private static final int N = 100;

The Repeat-Until-Sentinel Idiom

A better approach for the addition program that works for any

number of values is to use the Repeat-Until-Sentinel idiom,

which executes a set of statements until the user enters a specific

value called a sentinel to signal the end of the list:

while (true) {

prompt user and read in a value

if (value == sentinel ) break;

rest of loop body

You should choose a sentinel value that is not likely to occur in

the input data. It also makes sense to define the sentinel as a

named constant to make the sentinel value easy to change.

The AddIntegerList Program

public class AddIntegerList extends ConsoleProgram {

public void run() {

println("This program adds a list of integers.");

println("Enter values, one per line, using " + SENTINEL);

println("to signal the end of the list.");

int total = 0;

while (true) {

int value = readInt("? ");

if (value == SENTINEL) break;

total += value;

println("The total is " + total + ".");

private static final int SENTINEL = 0;

This program uses the Repeat-Until-Sentinel idiom to add a list

of integers, stopping when the user enters a value that matches

the named constant SENTINEL.

The AddIntegerList Program

public void run() {

println("This program adds a list of integers.");

println("Enter values, one per line, using " + SENTINEL);

println("to signal the end of the list.");

int total = 0;

while (true) {

int value = readInt("? ");

if (value == SENTINEL) break;

total += value;

println("The total is " + total + ".");

AddIntegerList

value total

This program adds a list of integers.

The total is 6.

? 1

to signal the end of the list.

? 2

? 3

? 0

Enter values, one per line, using 0

public void run() {

println("This program adds a list of integers.");

println("Enter values, one per line, using " + SENTINEL);

println("to signal the end of the list.");

int total = 0;

while (true) {

int value = readInt("? ");

if (value == SENTINEL) break;

total += value;

println("The total is " + total + ".");

value total

skip simulation

Exercise: Control Patterns

Using the AddIntegerList program as a model, write a new

AverageList program that reads a set of integers from the user

and displays their average. Because 0 values might well appear,

for example, in an average of exam scores, change the sentinel

value so that the input stops when the user enters - 1. It is

important to keep in mind that the average of a set of integers is

not necessarily an integer.

The AverageList program will require the following changes:

  • Convert the variable total to a double before computing the average
  • Change the definition of the SENTINEL constant
  • Keep a count of the number of input values along with the sum
  • Update the user messages and program documentation

The AverageList Program

public class AverageList extends ConsoleProgram {

public void run() {

println("This program averages a list of numbers.");

println("Enter values, one per line, using " + SENTINEL);

println("to signal the end of the list.");

int total = 0;

int count = 0;

while (true) {

int value = readInt("? ");

if (value == SENTINEL) break;

total += value;

count++;

double average = (double) total / count;

println("The average is " + average + ".");

private static final int SENTINEL = -1;

The if Statement

The simplest of the control statements is the if statement, which

occurs in two forms. You use the first form whenever you need

to perform an operation only if a particular condition is true:

if ( condition ) {

statements to be executed if the condition is true

You use the second form whenever you want to choose between

two alternative paths, one for cases in which a condition is true

and a second for cases in which that condition is false:

if ( condition ) {

statements to be executed if the condition is true

} else {

statements to be executed if the condition is false

The while Statement

The while statement is the simplest of Java’s iterative control

statements and has the following form:

while ( condition ) {

statements to be repeated

When Java encounters a while statement, it begins by evaluating

the condition in parentheses, which must have a boolean value.

If the value of condition is true, Java executes the statements in

the body of the loop.

At the end of each cycle, Java reevaluates condition to see

whether its value has changed. If condition evaluates to false,

Java exits from the loop and continues with the statement

following the closing brace at the end of the while body.

while ( condition ) {

statements to be repeated

The DigitSum Program

public void run() {

println("This program sums the digits in an integer.");

int n = readInt("Enter a positive integer: ");

int dsum = 0;

while ( n > 0 ) {

dsum += n % 10;

n /= 10;

println("The sum of the digits is " + dsum);

DigitSum

n dsum

This program sums the digits in an integer.

The sum of the digits is 19.

Enter a positive integer: 1729

public void run() {

println("This program sums the digits in an integer.");

int n = readInt("Enter a positive integer: ");

int dsum = 0;

while ( n > 0 ) {

dsum += n % 10;

n /= 10;

println("The sum of the digits is " + dsum);

n dsum

public void run() {

println("This program sums the digits in an integer.");

int n = readInt("Enter a positive integer: ");

int dsum = 0;

while ( n > 0 ) {

dsum += n % 10;

n /= 10;

println("The sum of the digits is " + dsum);

skip simulation

The Loop-and-a-Half Pattern

The while statement in Java always tests the condition at the

beginning of each cycle of the loop. Sometimes, however, you

need to perform some computation before you can make the test.

In those situations, the loop-and-a-half pattern is very useful:

while (true) {

computation necessary to make the test

if ( test for completion ) break;

computation for the rest of the loop cycle

Because the condition in the while statement itself is always

true, this loop would continue forever without some other

strategy to indicate completion. The loop-and-a-half pattern uses

the if and break statements to exit the loop. When the test for

completion becomes true, Java executes the break statement,

which causes the loop to exit, skipping the rest of the cycle.

Repeat-Until-Sentinel Revisited

The repeat-until-sentinel pattern presented at the beginning of the

chapter is an example of the loop-and-a-half pattern.

while (true) {

computation necessary to make the test

if ( test for completion ) break;

computation for the rest of the loop cycle

while (true) {

prompt user and read in a value

if (value == sentinel ) break;

rest of loop body

Although it might at first seem as if this pattern is more complex

than the more basic form of the while statement, it turns out to

be considerably easier for most students to use. Several studies

have demonstrated that students who use the loop-and-a-half

pattern are far more likely to write correct code than those who

don’t.

The for Statement

The for statement in Java is a particularly powerful tool for

specifying the control structure of a loop independently from the

operations the loop body performs. The syntax looks like this:

for ( init ; test ; step ) {

statements to be repeated

Java evaluates a for statement by executing the following steps:

1. Evaluate init , which typically declares a control variable.

2. Evaluate test and exit from the loop if the value is false.

3. Execute the statements in the body of the loop.

4. Evaluate step, which usually updates the control variable.

5. Return to step 2 to begin the next loop cycle.

for ( init ; test ; step ) {

statements to be repeated

Comparing for and while

The for statement

is functionally equivalent to the following code using while:

for ( init ; test ; step ) {

statements to be repeated

init ;

while ( test ) {

statements to be repeated

step ;

The advantage of the for statement is that everything you need

to know to understand how many times the loop will run is

explicitly included in the header line.

Exercise: Reading for Statements

Describe the effect of each of the following for statements:

This statement executes the loop body ten times, with the control

variable i taking on each successive value between 1 and 10.

1. for (int i = 1; i <= 10; i++)

This statement executes the loop body N times, with i counting from

0 to N - 1. This version is the standard Repeat-N-Times idiom.

for (int i = 0; i < N; i++)

This statement counts backward from 99 to 1 by twos.

3. for (int n = 99; n >= 1; n -= 2)

This statement executes the loop body with the variable x taking on

successive powers of two from 1 up to 1024.

4. for (int x = 1; x <= 1024; x *= 2)

The Countdown Program

public void run() {

for ( int t = 10 ; t >= 0 ; t-- ) {

println(t);

println("Liftoff!");

Countdown

t

10

9

8

7

6

5

4

3

2

1

0

Liftoff!

public void run() {

for ( int t = 10 ; t >= 0 ; t-- ) {

println(t);

println("Liftoff!");

skip simulation

public void run() {

for ( int t = 10 ; t >= 0 ; t-- ) {

println(t);

println("Liftoff!");

t

Nested for Statements

• The body of a control statement can contain other statements.

Such statements are said to be nested.

• Many applications require nested for statements. The next

slide, for example, shows a program to display a standard

checkerboard in which the number of rows and number of

columns are given by the constants N_ROWS and N_COLUMNS.

• The for loops in the Checkerboard program look like this:

for (int i = 0; i < N_ROWS; i++) {

for (int j = 0; j < N_COLUMNS; j++) {

Display the square at row i and column j.

• Because the entire inner loop runs for each cycle of the outer

loop, the program displays N_ROWS

x

N_COLUMNS squares.

The Checkerboard Program

public void run() {

double sqSize = (double) getHeight() / N_ROWS;

for (int i = 0; i < N_ROWS; i++) {

for (int j = 0; j < N_COLUMNS; j++) {

double x = j * sqSize;

double y = i * sqSize;

GRect sq = new GRect(x, y, sqSize, sqSize);

sq.setFilled((i + j) % 2 != 0);

add(sq);

sqSize i j x y sq

Execute the

inner loop

seven times to

complete the

checkerboard.

Execute these

statements six

more times to

complete the

row.

public void run() {

double sqSize = (double) getHeight() / N_ROWS;

for (int i = 0; i < N_ROWS; i++) {

for (int j = 0; j < N_COLUMNS; j++) {

double x = j * sqSize;

double y = i * sqSize;

GRect sq = new GRect(x, y, sqSize, sqSize);

sq.setFilled((i + j) % 2 != 0);

add(sq);

sqSize i j x y sq

skip simulation

Checkerboard

Exercise: Triangle Number Table

Write a program that duplicates the sample run shown at the

bottom on this slide, which displays the sum of the first N

integers for each value of N from 1 to 10. As the output suggests,

these numbers can be arranged to form a triangle and are

therefore called triangle numbers.

TriangleTable

1 = 1

1 + 2 = 3

1 + 2 + 3 = 6

1 + 2 + 3 + 4 = 10

1 + 2 + 3 + 4 + 5 = 15

1 + 2 + 3 + 4 + 5 + 6 = 21

1 + 2 + 3 + 4 + 5 + 6 + 7 = 28

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Design Issues: Triangle Number Table

• The program involves two nested loops. The outer loop runs

through each of the values of N from 1 to the maximum; the

inner loop prints a series of values on each output line.

As you think about the design of the TriangleTable program,

it will help to keep the following thoughts in mind:

• The individual elements of each output line are easier to

display if you call print instead of println. The print

method is similar to println but doesn’t return the cursor

position to the beginning of the next line in the way that

println does. Using print therefore makes it possible to

string several output values together on the same line.

• The n

th

output line contains n values before the equal sign but

only n – 1 plus signs. Your program therefore cannot print a

plus sign on each cycle of the inner loop but must instead

skip one cycle.