PPT

advertisement
COP3502
Programming
Fundamentals
for CIS Majors 1
Instructor: Parisa Rashidi
Agenda
 Sakai
 In
case of any problems, contact TA before due
date!
Previously ...
 Chapter
3
 Conditional
statements
 if
 if..else
 else
if
 switch
 Logical
 &&,
operators
||, ^, !
Objectives
 Chapter
4
 Loops
 while
 do-while
 for

Input from file
Loops
Motivation
 Suppose
we want to show “Java is fun!” 100
times. How do we do that?
 Repeat
the following statement 100 times!?
System.out.println("Welcome to Java!");
Naïve Solution
 Naïve
solution
System.out.println("Welcome
System.out.println("Welcome
System.out.println("Welcome
System.out.println("Welcome
System.out.println("Welcome
System.out.println("Welcome
100
times!
to
to
to
to
to
to
Java!");
Java!");
Java!");
Java!");
Java!");
Java!");
…
…
…
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
Better Solution
 Better solution
 Using loop
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}
Why Loops?
1.
To automate the repetition of calculations
E.g. compute the profit for “a number of different
months” of a company's sale
2.
To iterate through data and test for certain
condition
E.g. Checking input data, until user wants to “quit”
3.
To keep attempting for some operation
E.g obtaining data from a remote computer over a
network) until we succeed
while Loop
while Loop
while(condition)
{
statement;
}
1.
2.
3.
If the condition is true, the statement is
executed; then the condition is evaluated
again …
The statement is executed over and over
until the condition becomes false.
When the loop finishes, control passes to
the next instruction in the program,
following the closing curly brace of the loop.
while
while (loop-condition) {
// loop-body;
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
Statement(s);
count++;
}
}
count = 0;
Loop
Continuation
Condition?
true
Statement(s)
(loop body)
(A)
false
(count < 100)?
false
true
System.out.println("Welcome to Java!");
count++;
(B)
Trace Program
Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program
(count < 2) is true
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program
Print “Welcome to Java!”
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
count is now 1.
Trace Program
(count < 2) is still true.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program
Print “Welcome to Java!”
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
count is now 2.
Trace Program
(count < 2) is now false.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Trace Program
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Loop exit
Caution!
 No
; at the end of while
No ; here!
int count = 0;
while (count < 100)
{
System.out.println("Welcome to Java!");
count++;
}
Caution!
 The
body of a while loop must eventually
make the condition false
 If not, it is an infinite loop, which will execute
until the user interrupts the program!
int count = 1;
while (count > 0)
{
System.out.println("Welcome to Java!");
count++;
}
CAUTION!

Don’t use floating-point values for equality
checking in a loop control!

Floating-point values are approximations
double item = 1.0;
while (item != 0.0) {
// No guarantee item will be 0
item -= 0.1;
}

There is no guarantee that item will be
exactly 0: actually an infinite loop!
Tip
 Avoid
using literals directly in code as much as
possible (good programming style)
int count = 0;
final int REPEATS = 100;
while (count < REPEATS )
{
System.out.println(“Java");
count++;
}
System.out.println(REPEATS + “ Times” );
Tip
 To
repeat a loop 10 times, you generally write
a loop “not from 1 to 10”, but “from 0 to 9”.
 All counting in Java tends to start at zero
rather than one. This is a convention that
most Java programmers adopt.
 Again: good programming style
Program

Write a program that randomly generates an
integer between 0 and 100, inclusive. The
program prompts the user to enter a number
continuously until the number matches the
randomly generated number. For each user
input, the program tells the user whether the
input is too low or too high, so the user can
choose the next input intelligently.
GuessNumberOneTime
Run
GuessNumber
Run
Program
 Write
a program that prompts the user to
enter two positive integers and finds their
greatest common divisor.
GreatestCommonDivisor
Run
Program
 Suppose
that the tuition for a university is
$10,000 this year and tuition increases 7%
every year. In how many years will the tuition
be doubled?
FutureTuition
Run
Program


Often the number of times a loop is executed
is not predetermined. You may use an input
value to signify the end of the loop. Such a
value is known as a sentinel value.
Write a program that reads and calculates
the sum of an unspecified number of
integers. The input 0 signifies the end of the
input.
SentinelValue
Run
Program
A
sentinel-controlled loop can be
implemented using a confirmation dialog. The
answers Yes or No to continue or terminate
the loop. The template of the loop may look
as follows
int option = 0;
while (option == JOptionPane.YES_OPTION) {
System.out.println("continue loop");
option = JOptionPane.showConfirmDialog(null, "Continue?");
}
SentinelValueUsingConfirmationDialog
Run
Reading from file
Input Redirection
 What
if in previous example we wanted to
enter a long list of numbers?

We can store data (separated by whitespace) in a text
file
>java SentinelValue < input.txt
 This
is called “input redirection”
Output Redirection
 We
can also send output to a file rather than
displaying it on the console
>java ClassName > output.txt
 This
is called “output redirection”
 We can use “input redirection” and “output
redirection” in the same command
>java SentinelValue < input.txt >output.txt
Agenda
 HW
3 is due today
 PA 2 is due today
 HW 4 posted today
Previously …
 Loops
 while
 Input
 java
redirection
ClassFile <input.txt
 Output
 java
redirection
ClassFile >output.txt
Today
 Loops
 do-while
 for
Program

This example gives a program that generates
five questions and reports the number of the
correct answers after a student answers all
five questions.
SubtractionQuizLoop
Run
do-while Loop
do-while

Will be executed at least once
do {
Statement(s)
(loop body)
// Loop body;
Statement(s);
} while (loop-condition);
true
Loop
Continuation
Condition?
false
Caution!
;
at the end of while
int count = 0;
do
{
System.out.println("Welcome to Java!");
count++;
} while (count < 100) ;
; here!
CAUTION!

Do NOT add a semicolon at the end of the
while clause:
int i=0;
while (i < 10);
{
System.out.println(i);
i++;
}

int i=0;
do {
System.out.println(i);
i++;
} while (i<10);
BUT in case of do-while ; is required.
for Loop
for loop
int count = 0;
while (count < 10)
{
System.out.println("Welcome to Java!");
count++;
}
for(int count =0; count < 10; count ++)
{
System.out.println("Welcome to Java!");
}
for loop
for (initial-action;
continuation-condition;
action-after-each-iteration)
{
// loop body….
}
int i;
for (i = 0; i < 100; i++) {
System.out.println("Welcome to Java!");
}
Tip
 It
is common to declare the loop variable at
the start of the for loop itself:
for( int Count = 0; Count < 10; Count++ )
{
....;
}
for loop
Initial-Action
Loop
Continuation
Condition?
i=0
false
(i < 100)?
true
Statement(s)
(loop body)
true
System.out.println(
"Welcome to Java");
Action-After-Each-Iteration
i++
(A)
(B)
false
More Tips
 The
initial-action statement is carried out
once only, at the start of the first time that the
loop is entered.
 The continuation-condition is tested before
each execution of the body of the loop,
including a test before the very first execution
of the loop.
 The third expression (i.e action-after-eachiteration) is a statement executed after every
execution of the loop body, before the next
test. It typically increments a counter.
for Loop
Declare i
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
Execute initializer
i is now 0
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
(i < 2) is true
since i is 0
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Print Welcome to Java
for Loop
Execute adjustment
statement
i now is 1
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
(i < 2) is still true
since i is 1
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Print Welcome to Java
for Loop
Execute adjustment
statement
i now is 2
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
(i < 2) is false
since i is 2
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
for Loop
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Exit the loop. Execute the
next statement after the loop
CAUTION!

The initial-action in a for loop is a list of zero

The action-after-each-iteration in a for loop is

or more comma-separated expressions
a list of zero or more comma-separated
statements
Therefore, the following two for loops are
correct. They are rarely used in practice,
however.
for (int i = 1; i < 100; System.out.println(i++));
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
CAUTION!

If the loop-continuation-condition in a for
loop is omitted, it is implicitly true.
for ( ; ; ) {
// Do something
}
(a)
Equivalent
while (true) {
// Do something
}
(b)
CAUTION!

Do NOT add a semicolon at the end of the
for clause:
Don’t
do this!
for (int i=0; i<10; i++);
{
System.out.println("i is " + i);
}

(here ; is executed as for loop statement,
therefore we won’t see any output)
Program

Write a program that sums a series that
starts with 0.01 and ends with 1.0. The
numbers in the series will increment by 0.01,
as follows: 0.01 + 0.02 + 0.03 and so on.
TestSum
Run
Program

Write a program that uses nested for loops
to print a multiplication table.
MultiplicationTable
Run
Program
 The
Monte Carlo simulation refers to a technique that
uses random numbers and probability to solve
problems. This method has a wide range of
applications in computational mathematics, physics,
chemistry, and finance. This section gives an example
of using the Monto Carlo simulation for estimating .
y
circleArea / squareArea =  / 4.
1
-1
1
-1
x
 can be approximated as 4 *
numberOfHits / 1000000.
Using circle equation: 𝑥 2 + 𝑦 2 ≤ 1
MonteCarloSimulation
Run
Which Loop?

All loops are equal
while (loop-continuation-condition) {
// Loop body
}
Equivalent
for ( ; loop-continuation-condition; ) {
// Loop body
}
(a)
for (initial-action;
loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
}
(a)
(b)
Equivalent
initial-action;
while (loop-continuation-condition) {
// Loop body;
action-after-each-iteration;
}
(b)
Which Loop?

Some recommendations
1.
2.
3.
4.
Use the most intuitive loop
If number of repetitions known for
If number of repetitions unknown  while
If should be executed at least once (before
testing the condition)  do-while
Break/continue
break
causes the loop to be abandoned, and
execution continues following the closing
curly brace.
 break
while ( i > 0 )
{
....
if ( j == .... )
break; // abandon the loop
….
}
// end of the loop body
break will bring
you here
continue
causes the rest of the current
round of the loop to be skipped.
 continue
 "while"
or "do" loop moves directly to the
next condition test of the loop.
 "for" loop moves to the “action-after-eachiteration” expression, and then to the condition
test.
Continue/break
causes the rest of the current
round of the loop to be skipped.
 Break causes the loop to be skipped overall.
 continue
 Those
two keywords might be useful
sometimes
 But
they make programs more difficult to read
 So use them rarely
 Use
a boolean flag instead
Program
 Examples
keywords:

for using the break and continue
TestBreak.java
TestBreak

Run
TestContinue.java
TestContinue
Run
Program

Here is a program for guessing a number.
You can rewrite it using a break statement.
GuessNumberUsingBreak
Run
Program
 Write
a program that displays the first 50
prime numbers in five lines, each of which
contains 10 numbers. An integer greater than
1 is prime if its only positive divisor is 1 or
itself. For example, 2, 3, 5, and 7 are prime
numbers, but 4, 6, 8, and 9 are not.
PrimeNumber
Run
Download