Lecture 10, CS 302-6, September 26
- Review
- Boolean
operators
i.
De Morgan’s Law
ii.
String comparisons
- Input
Validation
- While
Loop
- Loop
ground rules
- Reminder:
if statements do something once.
While statements do something until the condition is
met. If loops don’t exist.
- Be
careful to avoid infinite loops
i.
Apple - one infinite loop
ii.
XKCD –
http://xkcd.com/140/
- Declare
variables before loop, if you need to access them afterwards
- Off-by-one-errors
i.
Be careful with <=, < etc in conditions
- Example
– BankAccount.java
- For
loops
- Special
case of a while loop
- For
when you know exactly how many times you have to do something
- Differences
from while loop:
i.
Count-controlled vs event controlled
ii.
Definite vs indefinite
- Structure:
For(int i=0;i<x;i++)
{
body
}
- Details:
i.
For( initialization; condition; update)
ii.
i is only declared within the for loop
1.
So, if you try to use it after the for loop is over, java will
crash
- Example
- Factorial.java
- For
loop – other uses/examples
- We
can do more than just count up in for loops
i.
Can count down, count up by 2, etc. i--, i+=2, etc.
ii.
Note – if we define counter before initialize, we can use it
afterwards
- So,
we can use for loops to count up to a certain number – similarly, we can
use them to traverse the characters in a string
- One
use – reversing a string
- Example
– Palindrome.java
- Do
Loop
- Almost
identical to a While loop.
i.
Doesn’t check condition before first iteration
ii.
Post-test instead of pre-test
do
{
}
while(condition);
- HW
- Read
4.4-4.5