Chapter 5: Loops - CSNetwork Services

download report

Transcript Chapter 5: Loops - CSNetwork Services

Chapter 5: Loops
Tarik Booker
CS 201
California State University, Los
Angeles
What we will cover…
•
•
•
•
•
•
•
•
•
•
Intro to loops
While loops
Loop design
Sentinels
Input / Output Redirections
The do-while Loop
The for Loop
Which Loop to use?
Nested Loops
break and continue
Introduction to Loops!
• Suppose you want to do something many
different times
▫ 5 times – 5 lines of code
▫ 10 times – maybe 10 separate lines of code
▫ 100, 1000 times?
 You can’t write the same lines of code so many
times.
 Instead, we use loops!
• Loops can be used to control how many times an
operation (or sequence) is performed
Introduction to Loops (2)
• Ex: You want to print something out 100 times
▫ Instead of copy/pasting the same line of code:
 System.out.println(“Welcome to Java!”);
▫ We say:
int count=0;
while (count < 100)
{
System.out.println(“Welcome to Java!”);
count++;
}
▫ We are using what’s called a while loop
The while Loop
while(loop_condition)
{
//Loop Body
Statements;
}
• The while loop continually executes the
statements within the block so long as the loop
condition is true
▫ As soon as the condition turns false, the loop is
stopped and the program continues
The while Loop (2)
• Terminology
▫ Loop continuation condition
 A condition that must be true in
order for the loop to repeat
 Boolean
▫ Loop body
 Part that contains statements to be
repeated
▫ Iteration
 A Single execution of the loop
 Also called a repetition
while(loop_condition)
{
//Loop Body
Statements;
}
The while Loop (3)
• If the loop condition in the while loop is true, the
loop will continue to iterate
while
(loop_condition)
Loop Body
Statements
The while Loop (4)
• Ex: Print out 100 numbers starting with zero.
▫ How to code?
▫ Write out all numbers
▫ Use a loop!
• We are doing something 100 times, so let’s start with a
counter
▫ Call it count
• We will make the counter keep track of how many times the
loop is running
▫ Increment the counter during the loop
• We will stop after 100 times
▫ Make the loop condition false after counter runs 100 times
• Start with zero
▫ Make counter start with 0.
The while Loop (5)
int count = 0;
while(count < 100)
{
System.out.println(count);
count++;
}
• We have used count as output, but also to keep
track of the loop
▫ This is called a counter-controlled loop
The while Loop (6)
• What about these examples?
int sum =0, i=1;
while(i<10)
{
sum = sum + i;
i++;
}
System.out.println(“Sum is “+sum);
int sum =0, i=1;
while(i<10)
{
sum = sum + i;
}
System.out.println(“Sum is “+sum);
The while Loop (7)
• The first example works how we want, but the
second results in an infinite loop!
▫ A loop that doesn’t stop
▫ Your program runs forever!
▫ Avoid!
• What happens here?
▫ while(true);
Off by One Errors
• Any time you add/sum/multiply/account for a
long interval of numbers, you run the risk of an
“Off by one error”
▫ You have run your loop one more or less time than
expected
• Ex:Display “Welcome to Java” 100 times
▫ (Incorrect) Answer:
 Why?
int count=0;
while(count <= 100)
{
System.out.println(“Welcome to Java!”);
count++;
}
Off by One Errors
• Let’s look at this again:
int count=0;
while(count <= 100)
{
System.out.println(“Welcome to Java!”);
count++;
}
▫ Count starts with 0
▫ Loop ends with count less than or equal to 100
 This includes 100
▫ Therefore the while loop executes from 0 to 100
times, including both 0 and 100
 Loop actually executes 101 times
Loop Design Strategies
• Loops can be hard if you don’t plan for them
• Strategies:
▫ Identify the statements that need to be repeated
▫ Wrap those statements in a loop block
▫ Code the loop condition and add statements for
controlling the loop
1
2
3
while(loop_condition)
{
// Loop body
// Statements;
}
Example
• Let’s look at the Guess Number example
▫ p162
Controlling a Loop with a Sentinel
Value
• So far, we’ve used a counter to control a loop
• Now we use sentinels
▫ Sentinels are special variables that you designate
to signal the end of a loop
• Use by creating a variable to designate as a
sentinel
▫ Select a value to represent the end of a loop
• Called a sentinel-controlled loop
Controlling a Loop with a Sentinel
boolean sentinel=true; //sentinel
Value (2)
while(sentinel)
{
//Statements;
// When I’m done:
sentinel = false;
}
• Sentinels are easy to use
▫ Create a variable;
 int, boolean, fine
▫ Give the sentinel an initial value
▫ Make the loop true so long as the sentinel is that
value
▫ Change the sentinel value when you’re done.
Controlling a Loop with a Sentinel
Value (3)
• Let’s look at an example:
▫ P166
▫ SentinelValue.java
Possible Errors
• Don’t use floating-point values for equality
checking in a loop control!
▫ Floating point values are approximations for some
values
▫ May not give correct results
 Infinite loop!!!
Input/Output Redirections
• You can type in inputs from a file simulating
console input.
▫ Called input redirection
▫ Use < to designate input from a file directly to
your program (used like console input)
• Ex:
▫ java SentinelValue < input.txt
▫ Takes the values from input.txt and uses them like
console input
▫ Make sure you use spaces between values in your
file!
Input/Output Redirections (2)
• You can automatically save the output of a program
in a file using output redirection
▫ Use > to put the results of a program directly into a file
• Ex:
▫ java ClassName > output.txt
• Note: You can use both input and output redirection
at the same time
• Ex:
 java SentinelValue <input.txt > output.txt
 java SentinelValue > output.txt < input.txt
The do-while Loop
• The do-while is the same as the while loop, but it
executes it’s loop body first
do
{
//Loop body
//Statements;
} while(loop_condition);
• Use the same way as the while loop, but for when
you need to execute the body at least once
▫ Typically for checking bad input
▫ Not used often
▫ Don’t forget the semicolon(;) after the while portion!!!
The do-while Loop (2)
• Typical use of a do-while loop:
Scanner input = new Scanner(System.in);
do //read in data until it’s 0
{
System.out.println(“Enter an integer. Ends at 0: ”);
data = input.nextInt();
} while(data!=0);
• The program allows you to enter in values until
zero
▫ Program then continues
▫ You can use it to verify data
The for Loop
• The for loop has a detailed way of constructing a
loop
▫ That’s it. There’s nothing additional to the logic of
a for loop
• Structure:
for(initial_action; loop_condition; action_after_iteration)
{
//Loop body
//Statements;
}
▫ Keep in mind: there’s no difference in logic, just
the structure of the for loop
The for Loop
for
for loop steps:
•
•
•
•
•
(
Initial action
;
Loop condition
{
Initial action (or
initialization
Check the loop condition
Execute loop body
Perform action after
iteration
Check loop condition
again: If still true,
}
execute loop body again
and repeat
Loop Body
;
Action after
iteration
)
for Loop Examples
• Typical for Loop Structure:
for(i = initialValue; i<endValue; i++)
{
//Loop body
}
▫ We are using i as a loop counter. However, we
now initialize i in the initial action, increment i in
the iteration action, and limit a value on i in the
loop condition
for Loop Examples (2)
• Ex:
times!
• Ans:
Let’s print “Welcome to Java!” 100
int i;
for(i = 0; i<100; i++)
{
System.out.println(“Welcome to Java!”);
}
▫ This is a simplified way of performing the earlier
loop
 What’s our initial action?
 Loop condition?
 Action after initialization?
for Loop Examples (3)
• You can declare a new variable in the initial
action:
▫ Compare:
int i;
for(i = 0; i<100; i++)
{
System.out.println(“Welcome to Java!”);
}
for(int i = 0; i<100; i++)
{
System.out.println(“Welcome to Java!”);
}
for Loop Examples (4)
• The initial action, and the action after iteration
can both include a list of zero or more commaseparated statements
▫ Initial action: Zero or more variable declaration
statements or assignment expressions
for(int i = 0, j = 0; i + j<10; i++, j++)
{
//Something
}
for Loop Examples (5)
• Action after iteration: Zero or more commaseparated statements:
for(int i = 1; i<100; System.out.println(i), i++);
• Note: Don’t do this too much, or else your
program will be unreadable
For loop Weirdness
• Speaking of, what are the results of these for
loops:
▫ for(;;)
▫ for(; true;)
▫ while(true);
• People will ask for this on a job interview!
▫ Xerox
For Loop Weirdness (2)
• Keep in mind, any legal assignment statement,
conditional, and statement can be placed in a for
loop. for(variable declaration or assignment; conditional; statement);
• Is this legal?
for(int x = 5;”Test”.equals(“Test”); System.out.println(“Hello”));
for(String z=“Hello”;true; number = input.next());
Which loop to use?
• While, for loops called pretest loops
▫ Loop condition is checked before loop body is
executed
• Do-while loop called posttest loop
▫ Loop condition is checked after loop body is executed
• While, d0-while, and for loops are expressively
equivalent
▫ You can write a loop is any of these forms
▫ You can always convert a while loop to a for loop
Which loop to use? (2)
• Use the loop structure that’s best for you!
▫ Nothing requires a specific type of loop
▫ It only depends on your preference
 Or ease!
Nested Loops
• You can have nested loops!
▫ Loops within loops
• How does it work!
▫ Think in terms of outer / inner
▫ For each iteration of the outer loop, the inner loop
runs fully
Nested Loops (2)
for(int x=0; x<3; ++x)
{
for(int y=0; y<100; ++y);
}
Iteration:
x=0
Iteration:
x=1
Iteration:
x=2
for(int y=0; y<100;
++y);
for(int y=0; y<100;
++y);
for(int y=0; y<100;
++y);
//Runs 100
times
//Runs 100
times
//Runs 100
times
How many times does the whole thing run?
Nested Loops (3)
• The last loop ran the inner loop every time per
iteration of the outer.
▫ Nouter iterations x Ninner iterations
▫ Multiply each total inner by each outer
• How many times does this loop run?
for (int x=0; x<10000; ++x)
for(int y=0; y<10000; ++y)
for(int z=0; z<10000;++z)
System.out.println(x+y+z);
Minimizing Numeric Errors
• There are many many potential errors when it
comes to using floating-point numbers in loop
conditions
▫ We can minimize errors, but will never be free of
them
• Look at this code snippet:
for(float i = 0.01; i<= 1.0f; i=i+0.01f)
sum +=i;
System.out.println(“Sum = “+sum);
▫ What is the result?
Minimizing Numeric Errors (2)
for(float i = 0.01f; i<= 1.0f; i=i+0.01f)
sum +=i;
System.out.println(“Sum = “+sum);
• The sum should be 50.50, but is actually
50.499985
▫ Why? Precision errors.
• Change the type to double:
▫ What is the result?
for(double i = 0.0; i<= 1.0; i=i+0.01)
sum +=i;
System.out.println(“Sum = “+sum);
Minimizing Numeric Errors (3)
for(double i = 0.0; i<= 1.0; i=i+0.01)
sum +=i;
System.out.println(“Sum = “+sum);
▫ Result is: 49.50000000003!
• What’s going on?
▫ Floating-point numbers are approximations!
• Stick to integers when using loop counters
Break and continue
• You can use break and continue to provide
additional controls
▫ Break
 Completely ends the loop
 We used this in a switch statement (remember!!!)
▫ Continue
 Ends the current iteration of the loop
 Goes to the next iteration
Break and continue (2)
• Look at TestContinue.java
▫ p184-185
• Ex: (p185) Find the smallest factor other than 1
for an integer n
▫ You can use break for this:
int factor=2;
while(factor <= n)
{
if(n%factor == 0)
break;
factor++;
}
System.out.println(“The smallest factor other than 1 for “+n+” is “+factor);
Loops are important!
• Loops are used almost everywhere in
programming!
• They are very important!
• I will give you tons of loop work in this class!
▫ They will be used continuously afterward!
• Good luck!