week 5: loops 1. repetition is the ability to do something over and over again with repetition in...
TRANSCRIPT
2
Repetition
Repetition is the ability to do something over and over again
With repetition in the mix, we can solve practically any problem that can be solved with a computer
Repetition leverages the most famous ability of the computer: speed
3
Mechanics
The main way that repetition works in Java is through loops
A loop is a block of code that will be executed repeatedly some number of times (perhaps even zero times!)
As the statements are executed, variables may change
It isn’t just repeating the same thing over and over
4
while loop
The simplest loop in Java is the while loop
It looks similar to an if statement The difference is that, when you get
to the end of the while loop, it jumps back to the top
If the condition in the while loop is still true, it executes the body of the loop again
5
Anatomy of a while loop
while( condition ){
statement1;statement2;…statementn;
}
A whole bunch of
statements
6
A while loop with only one statement
A while loop will usually have multiple statements in its body
However, it is possible to make a while loop with only a single statement
Then, like an if-statement, the braces are optional
while( condition ) statement;
7
Printing numbers
Let’s print the numbers from 1 to 100
int i = 1;
while( i <= 100 ){System.out.println(i);i++;
}
8
Rules for while
The while loop checks if the condition is true, and if so, executes each statement one by one
When execution gets to the bottom, it jumps back up to the top
If the condition is still true (i.e., i <= 100), it repeats the loop
9
Workings of a while loop
//line Awhile( condition ){
//line Bstatement1;statement2;//line C…statementn;
}//line D
Line Condition
A n
B
C
D
Line Condition
A Unknown
B
C
D
Line Condition
A Unknown
B True
C
D
Line Condition
A Unknown
B True
C Unknown
D
Line Condition
A Unknown
B True
C Unknown
D False
10
Summing numbers
We can also use while loops to help us deal with input
What if we wanted to sum all of the numbers that a person entered?
How would we know when to stop? One solution is to keep adding
numbers until the person enters a negative number
This is called using a sentinel value
11
Summing numbers
Solution:
int i = 0;int sum = 0;
while( i >= 0 ){sum += i;System.out.print(“Enter number: “);i = StdIn.readInt();
}System.out.println(“Sum: “ + sum);
12
Finding the average
We could also find the average:int i = 0;double sum = 0;int count = 0;
while( i >= 0 ){sum += i;count++;System.out.print(“Enter number: “);i = StdIn.readInt();
}count--; //fixes extra count for sentinelSystem.out.println(“Average: “ + (sum / count));
13
Tracking the biggest input
What if we wanted to find the biggest input?
Somehow we would have to check each input and see if it were larger than the current largest
Solution: use an if-statement inside of a while loop
if (i > iBig) iBig = i;
14
Guessing game
Let’s say that you wanted to write a program to guess a number that a person had come up
The number is between 1 and 100 Every time the computer guesses a
number, the person enters: H if the number is too high L if the number is too low F if the number was found
15
Guessing game algorithm
1. Start with the minimum and maximum of the range
2. Find the midpoint3. Ask the user if the midpoint is correct4. If the answer is too high, go to Step 1
using the minimum and the midpoint as the new range
5. If the answer is too low, go to Step 1 using the midpoint and the maximum as the new range
6. If the midpoint is correct, you’re done!
16
Nested loops
Just as with if-statements, it’s possible to nest loops
A repetitive task can be done inside of another repetitive task
18
Infinite loops
Loops can go on forever if you aren’t careful
int n = 40;int i = 1;
while( i <= n ){System.out.println(i);//supposed to print all the numbers//less than 40, but i never increases
}
19
Badly-written loops
int n = 40;int i = 1;
while( i <= n ){System.out.println(i);i--; //woops, should have been i++
}
20
Fencepost errors
Being off by one is a very common loop error
int n = 40;int i = 1;
while( i < n ) //won’t //reach n
{System.out.println(i);i++;
}
21
Skipping loops entirely
If the condition isn’t true to begin with, the loop will just be skipped
int n = 40;int i = 1;
while( i >= n ) //oops, should be <={System.out.println(i);i++;
}
22
Misplaced semicolon
A misplaced semicolon can cause an empty loop body to be executed (often infinitely)int n = 40;
int i = 1;
while( i <= n ); //semicolon is wrong{System.out.println(i);i++;
}
23
3 loops in Java
1. while loops Used when you don’t know how many
times you are going to need to repeat2. for loops
Used when you do know how many times you are going to repeat
3. do-while loops Used almost never Oh, okay, they are used whenever you need
to be guaranteed the loop runs at least once
24
Loops are interchangeable
Any problem that uses loops can use any kind of loop
The choice is supposed to make things easier on the programmer
Some loops are more convenient for certain kinds of problems
25
for loops
for loops are great when you know how many times a loop will run
They are the most commonly used of all loops
They are perfect for any task that needs to run, say, 100 times
A for loop has 3 parts in its header:1. Initialization2. Condition3. Increment
26
Way to Progress
Ending Point
Starting Point
Anatomy of a for loop
for( init; condition; inc ){
statement1;statement2;…statementn;
}
27
A for loop will usually have multiple statements in its body
However, it is possible to make a for loop with only a single statement
Then, like if-statements and while-loops, the braces are optional
for( init; condition; inc )statement;
A for loop with only one statement
28
for loop example
Let’s print the numbers from 1 to 100 (again)
Remember how this was done with while:
i = 1;
while( i <= 100 ){System.out.println(i);i++;
}
29
for loop example
A for loop is specifically designed for this sort of thing:
The initialization and the increment are built-in
for( i = 1; i <= 100; i++ ){System.out.println(i);
}
30
Finding primes
To see if a number is prime, we can divide by all the numbers less than the number to see if it can be evenly divided
Sounds like a perfect opportunity for a for loop
31
Testing for a prime
The following code will tell you if a number isn’t prime
What’s the problem?
int number = StdIn.readInt();
for( int i = 2; i < number; i++){if( number % i == 0 ){
System.out.println(number + “ is not prime.”);
}}
32
Better testing for a prime
By adding a boolean, we can keep track of whether or not the number is prime
int number = StdIn.readInt();boolean prime = true; for( int i = 2; i < number && prime; i++){if( number % i == 0 )
prime = false;}
33
do-while loops
They work just like while loops The only difference is that they are
guaranteed to execute at least once Unlike a while loop, the condition
isn’t checked the first time you go into the loop
Sometimes this is especially useful for getting input from the user
The syntax is a little bit different
35
Common pitfalls
Almost all of these are issues with while, for and do-while loops as well
Many of these errors have to do with incorrect starting or ending conditions for the loop
36
Infinite loops
Loops can go on forever if you aren’t careful
int n = 40;int i = 1;
do{System.out.println(i);//supposed to print all the numbers//less than 40, but i never increases
} while( i <= n );
37
Infinite for loops
for( int i = 0; i < 10; i++ ){System.out.println(i);//lots of other codei--; //woops
}
38
Bad increment
int i;
for( i = 1; i <= 40; i-- )//woops, should have been i++System.out.println(i);
39
Fencepost errors
Being off by one is a very common loop error
int i;
for( i = 1; i < 40; i++ )//runs 39 timesSystem.out.println(i);
40
Skipping loops entirely
If the condition isn’t true to begin with, the loop will just be skipped
for( int i = 1; i >= 40; i++ ) //oops, should be <=System.out.println(i);