Download Lecture notes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Lecture 05
Loops!
Why Loops?
•
Allow for better user interaction
•
Make code much cleaner
•
Save time copying/pasting
Types of loops
•
We’ll be using 3 different kinds of loops in this class:
•
While
•
Do…while
•
For
While Loop
•
while loops execute statements repeatedly while a
condition is true
while (loop-continuation-condition) {
statement(s);
}
While Loop
Infinite Loop
public class WhileLoopExample {
public static void main(String[] args) {
while (true){
System.out.println("Hello!");
}
}
}
Counter-controlled
Loop
public class WhileLoopExample {
public static void main(String[] args) {
int count = 0;
while (count < 10){
System.out.println("Hello " + (count+1) + " times!");
count++;
}
}
}
Increment counter
Off by one errors
Loop Design Strategies
•
Step 1: Figure out which parts need to repeat
•
Step 2: Put those statements inside a loop block
•
Step 3: Figure out the loop-continuation condition and
statements for controlling the loop (increment, etc)
Guess the Secret Word
- with Loop
import java.util.Scanner;
public class GuessSecretWord_Loop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String secretWord = "SECRET";
String userGuess;
System.out.println("Try to guess my secret word");
userGuess = input.nextLine();
while (!userGuess.equals(secretWord)){
System.out.println("NOPE. Try again!");
userGuess = input.nextLine();
}
System.out.println("Great job!");
}
}
example of
sentinel-controlled
loop
Do-While Loop
•
Same as while loop - but checks loop-continuation
condition at the end of the loop
do {
statement(s);
} while (loop-continuation-condition);
Do-While Loop
Guess the Secret Word
- with Do While Loop
import java.util.Scanner;
public class GuessSecretWord_DoWhileLoop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String secretWord = "SECRET";
String userGuess;
do {
System.out.println("Try to guess my secret word");
userGuess = input.nextLine();
} while (!userGuess.equals(secretWord));
System.out.println("Great job!");
}
}
While vs. Do-while?
•
Use a Do-while if the statements in the loop should
execute at least once
•
One might be more convenient (less code), or make a
little better experience for your users.
•
I see and use while loops much more often than dowhile loops, though they definitely have their place
For Loop
•
Simplify counter-controlled loops (helps prevent errors)
•
Very useful when the number of times to run is known
beforehand
for (initial-action; loop-continuation-condition; action-after-each-iteration)
statement(s);
}
For Loops
•
Often looks something like this:
for (int i = initialValue; i < endValue; i++) {
statement(s);
}
Simple For Loop
Example
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 0; i < 10; i++){
System.out.println(i);
}
}
}
Which Loop?
•
Guess a number until you’re right
•
Calculating the perimeter of a rectangle from user input
•
Adding all the digits from 0-9
•
Game loop
Which Loop?
•
The fact is, you can use any of them. But one might make
more sense than the others, given your circumstances
Nested Loops
•
Every time the outer loop is repeated, the inner loop
starts over
Nested Loops
public class NestedLoopExample {
public static void main(String[] args) {
// Outer loop of "rows"
for (int i = 0; i < 5; i++){
// Inner loop of "columns"
for (int j = 0; j < 5; j++){
// Print *
System.out.print("*");
}
// Go to next "row"
System.out.println("");
}
}
}
When to use nested
loops
•
Structured data (Arrays, tables, Maps, etc)
•
working with pixel array (graphics programming)
•
I use these all the time
Break and Continue
•
Keywords to control flow in
loops
•
break = immediately get out of
entire loop
•
continue = get out of current
iteration, keep looping
Break and Continue
public class BreakAndContinueExample {
public static void main(String[] args) {
String message = "Hey, this thing is a string";
for (int i = 0; i < message.length(); i++){
char currentChar = message.charAt(i);
if (currentChar == ' '){
break;
} else {
System.out.print(currentChar);
}
}
}
}
Loopify Fizz Buzz lite
•
Let’s go back to Fizz Buzz and have it run from 1 to 100
instead of asking for a number
Loopify Fizz Buzz lite
import java.util.Scanner;
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i < 101; i++){
if (i % 3 == 0 && i % 5 != 0){
System.out.println("Fizz");
} else if (i % 5 == 0 && i % 3 != 0){
System.out.println("Buzz");
} else if (i % 3 == 0 && i % 5 == 0){
System.out.println("FizzBuzz");
} else {
System.out.println(i);
}
}
}
}
Find ✨perfect✨ numbers
•
a number is considered perfect if it is equal to the sum of
all it’s positive divisors, except itself.
•
so 6 is a perfect number since 6 = 3 + 2 + 1
•
These are very rare, only 4 exist below 10,000
•
Let’s find them using loops!
Find ✨perfect✨ numbers
public class PerfectNumberFinder {
public static void main(String[] args) {
// Loop through all the numbers
for (int i = 1; i < 10000; i++){
// for each number, start a new sum
int sum = 0;
// for each number, check all the numbers smaller than that to see if it's a
divisor
for (int j = 1; j < i; j++){
if (i % j == 0){
sum += j;
}
}
// if the sum is equal to the number, you found a perfect one!
if (sum == i){
System.out.println("Found a perfect number: " + i + "!");
}
}
}
}
Find the next leap years
•
Write a program that will ask the user for a year to
start with and how many leap years they would like to
find.
•
Using a loop, display the year if it’s a leap year for the
amount of leap years requested.
•
Tip: A leap year happens every 4 years, but not every 100
years, then again every 400 years.
Find the next leap years
import java.util.*;
public class FindNextLeapYear {
public static void main(String[] args) {
int numberOfLeapYearsToFind;
int userYear;
Scanner input = new Scanner(System.in);
System.out.print("Enter the year you'd like to start from: ");
userYear = input.nextInt();
System.out.print("Enter how many leap years you'd like to find: ");
numberOfLeapYearsToFind = input.nextInt();
int foundLeapYears = 0;
while (foundLeapYears < numberOfLeapYearsToFind){
if (((userYear % 4 == 0) && (userYear % 100 != 0)) || userYear % 400 == 0){
foundLeapYears++;
System.out.println(userYear);
}
userYear++;
}
}
}