Lecture 10, CS 302-7 and 8, February 13
- Reminders
- Office
hours – 4-5
- Program
1
i.
Due February 24
- Review
- Boolean
operators
i.
De Morgan’s Law
- Basic
Input Validation
- While Loop
- General loop guidelines
- Reminder:
if statements do something once.
While statements do something until the condition is met. No if loop!
- Be
careful to avoid infinite loops
- Declare
variables outside of loop (before)
i.
This will help avoid scope issues
- Off-by-one-errors
i.
Be careful with <=, < etc in conditions
- Example
– AreWeThereYet.java
- For
loops
- Really
just one 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(<initialization>;<condition>;<update>)
{
//body
}
- Details:
i.
Three expressions: initialization, condition, update
ii.
Body is executed between the condition and update
iii.
The variable that we initialize in the <initialization>
step is only declared within the for loop
1.
So, we can’t do:
for(int a=0;a<10;a++) {
//Do
something
}
S.o.p(a);
- Example
- Factorial.java
- For
loop – more complex example
- We
can do more than just count up in for loops, update
i.
Can count down, count up by 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
- Helpful
string methods
i.
string.toUpperCase()
ii.
string.substring(start, end)
iii.
string.charAt(index)
iv.
string.length()
- HW
- Read
4.4