0% found this document useful (0 votes)
48 views

IntroCS Part 4

The document discusses conditionals and loops in programming. It provides examples of if, if-else statements for tasks like checking values and calculating rates. It also discusses while loops, explaining that they allow repetitive tasks to be specified concisely. An example program uses a while loop to print the powers of two up to 30, illustrating how loops repeat a statement until a condition is no longer true. Tracing program execution by listing variable values at each step is presented as a way to understand how loops work.

Uploaded by

Alfred Fred
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

IntroCS Part 4

The document discusses conditionals and loops in programming. It provides examples of if, if-else statements for tasks like checking values and calculating rates. It also discusses while loops, explaining that they allow repetitive tasks to be specified concisely. An example program uses a while loop to print the powers of two up to 30, illustrating how loops repeat a statement until a condition is no longer true. Tracing program execution by listing variable values at each step is presented as a way to understand how loops work.

Uploaded by

Alfred Fred
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Conditionals and Loops

45

Class Flip in Program 2.2.1 is an example of the use of the if-else statement, for the simple task of simulating a coin flip. To digress slightly, we note
that this simple program introduces an interesting philosophical issue that is
worth contemplating: Can we get a computer to produce random values? We
will return to this question on several occasions, because having numbers
with the properties of random numbers is critical for many practical applications.
The following table contains some more examples of the use of if
and if-else statements. These examples are typical of simple calculations
that you might need in programs that you write. They include examples of
simple functions and checks for possible error conditions in input data. Since
the semantics (meaning) of statements like these is similar to their meanings
as natural-language phrases, you will quickly grow used to using them.
absolute value
maximum of x and y

income tax rate

error check before


arithmetic operation

error check for


quadratic formula

if (x < 0) x = -x;
if (x > y) max = x;
else
max = y;
if
(income < 47450) rate = .22;
else if (income < 114650) rate = .25;
else if (income < 174700) rate = .28;
else if (income < 311950) rate = .33;
else
rate = .35;
if (d == 0)
System.out.println(Division by zero);
else
System.out.println(Quotient is + n/d);
d = b*b - 4.0*c;
if (d < 0.0)
System.out.println(No real roots);
else
{
d = Math.sqrt(d);
System.out.println((-b + d)/2.0);
System.out.println((-b - d)/2.0);
}

46

The if and if-else statements have the same status as assignment statements or any other statements in Java. That is, we can use them whenever a
statement is called for. However, when we use an if statement as <statement T> or <statement F> within another if statement (as in the incometax-rate example in the table), we have to be careful to resolve ambiguities
when doing so. This issue and more examples are addressed in the Q&A and
exercises at the end of this section.
One way to understand control flow is to
visualize it with a diagram called a flowchart,
yes
no
like the one at left. Paths through the flowx > y ?
chart correspond to flow-of-control paths in
max = y;
max = x;
the program. In the early days of computing,
when programmers used low-level languages and difficult-to-understand flows of
control, flowcharts were an essential part of
programming. With modern languages, we
Flow of control for the statement
if (x > y) max = x;
use flowcharts just to understand basic
else
max = y;
building blocks like the if-else statement.
While loops. Many computations are inherently repetitive. The basic Java
construct for handling such computations has the following format:
while (<boolean expression>) <statement>

The while statement has the same form as the if statement (the only difference being the use of the keyword while instead of if), but the meaning is
quite different. It is an instruction to the computer to behave as follows: if the
expression is false, do nothing; if the expression is true, execute the statement (just as with if) but then perform the same operation and continue
until the expression is not true any more. In other words, the while statement is equivalent to a sequence of identical if statements:
if (<boolean expression>) <statement>
if (<boolean expression>) <statement>
if (<boolean expression>) <statement>

...

An Introduction to Computer Science

Conditionals and Loops

Program 2.2.2

47

Your first while loop

public class TenHellos


{
public static void main(String[] args)
{
System.out.println(1st Hello);
System.out.println(2nd Hello);
System.out.println(3rd Hello);
int i = 4;
while (i <= 10)
{
System.out.println(i + th Hello);
i = i+1;
}
}

This program uses a while loop for


the simple repetitive task of printing
the ouput shown at right. After the
third line, the lines to be printed differ only in the value of the index
counting the line printed, so we define
a variable to contain that index and
increment it each time through the
loop to get the job done.

% javac TenHellos.java
% java TenHellos
1st Hello
2nd Hello
3rd Hello
4th Hello
5th Hello
6th Hello
7th Hello
8th Hello
9th Hello
10th Hello

At some point, the statement must change something (such as the value of
some variable in the expression) to make the expression false, and then the
sequence is broken.
There is a profound difference between programs with while statements and programs without them, because while statements allow us to
specify a potentially unlimited number of different possible sequences of
statements to be executed in a program. In particular, the while statement
allows us to specify lengthy computations in short programs. This ability
opens the door to writing programs for all manner of tasks. But there is also

48

Program 2.2.3

Computing powers of two

public class PowersOfTwo


{
public static void main(String[] args)
{
int i = 0;
int N = 1;
while (i <= 30)
{
System.out.println(i + + N);
i = i + 1;
N = 2 * N;
}
}
}

This program prints a table of the


powers of two in the Java int data
type. Each time through the loop, the
value of i is incremented by 1 and the
value of N is doubled. To save space,
we show only the first four and the last
two lines of the table at right; the program prints a 31-line table.

% javac PowersOfTwo.java
% java PowersOfTwo
0 1
1 2
2 4
3 8
...
29 536870912
30 1073741824

a price to pay: as your programs become more sophisticated, they become


more difficult to understand.
For a simple example that uses a while statement, consider class
in Program 2.2.2, which performs a simple task that could be
accomplished with a sequence of nearly identical System.out.println
statements. According to the template just given, the while loop is equivalent
to a sequence of copies of the statement
TenHellos

if (i <= 10) { System.out.println(i + th Hello); i = i+1; }

In this case, the statement is executed seven times and the sequence broken
when the value of i becomes 11. Using the while loop is barely worthwhile

An Introduction to Computer Science

Conditionals and Loops

49

for this specific simple task, but you will very soon be addressing tasks where
you will need to use while loops to specify that statements be repeated far
too many times to contemplate doing so any other way.
Class PowersOfTwo in Program 2.2.3 uses a while loop to print out a
table of the powers of 2. This code is the prototype for many useful computations: by varying the computations that change the accumulated value and
the way that the loop control variable is incremented, we can print out tables
of a variety of functions (see Exercise 2.2.10 and Exercise 2.2.11).
It is worthwhile to examine the behavior of Program 2.2.3 carefully,
to learn how to think about the behavior of programs with loops. A triedand-true method for checking that a program is behaving as we expect is
known as tracing the program. For example, the following table is a trace of
the operation of Program 2.2.3. It shows the value of each of the variables
before each iteration of the loop (and, for emphasis, the value of the conditional expression that controls the loop).
i

i <= 30

i <= 30

i <= 30

true

true

11

2048

true

21

2097152

true

true

12

4096

true

22

4194304

true

true

13

8192

true

23

8388608

true

16

true

14

16384

true

24

16777216

true

32

true

15

32768

true

25

33554432

true

64

true

16

65536

true

26

67108864

true

128

true

17

131072

true

27

134217728

true

256

true

18

262144

true

28

268435456

true

512

true

19

524288

true

29

536870912

true

10

1024

true

20

1048576

true

30

1073741824

true

31

false

At first, tracing can seem tedious, but it is worthwhile because it clearly


exposes what a program is doing. This program is nearly a self-tracing program, because it prints the values of its variables each time through the loop. 1

You might also like