U4 | Iteration
while Loops, for Loops, Developing Algorithms Using Strings, Nested Iteration, Informal code analysis >>> AP Exam Weighting 17.5-22.5%
- U4 | Iteration
- 4.1 while Loops
- 4.2 for Loops
- for Loops vs. while Loops
- 4.3 Developing Algorithms Using Strings
- Finding a substring within a string
- I T E R A T E
- POPCORN HACK: Run the code.. what happened? How can we fix it?
- The error stems from the for loop going until the length of the word even though the length of the word has an index that goes outside of the indexs of a word. To fix it we should change the for loop to instead have word.length - sub.length
- Another Issue: What if our substring was the word “RATE”? Note that RATE is at the end of the whole string.
- The code would not work as intended because it would stop at the first 'e' to fix this change it to <=
- HACKS
U4 | Iteration
4.1 while Loops
- A while loop is a fundamental control structure in programming used for repeated execution of a block of code as long as a condition is true.
- The loop starts by evaluating the condition. If the condition is true, the code inside the loop is executed.
- After each iteration, the condition is re-evaluated, and if it’s still true, the loop continues. If the condition is false initially, the loop code is never executed.
- While loops are used when you don’t know in advance how many times the loop needs to execute.
- There’s a risk of infinite loops if the condition never becomes false, so be cautious. You can use variables and complex expressions as loop conditions.
- It’s essential to update the loop control variable within the loop to prevent infinite loops.
- While loops are typically used for tasks such as iterating over collections or waiting for a specific condition to be met.
- You can always break out of a while loop prematurely using the break statement.
Example of While Loops
public class PyramidPattern {
public static void main(String[] args) {
int height = 5;
int row = 1;
while (row <= height) {
int spaces = height - row;
int stars = 2 * row - 1;
// Print spaces
int spaceCount = spaces;
while (spaceCount > 0) {
System.out.print(" ");
spaceCount--;
}
// Print stars
int starCount = stars;
while (starCount > 0) {
System.out.print("*");
starCount--;
}
System.out.println(); // Move to the next line for the next row
row++;
}
}
}
PyramidPattern.main(null);
*
***
*****
*******
*********
4.2 for Loops
- Iterative statement that checks for condition
- Repeatedly execute a a block of code as long as the condition is met
- Condition specifies amount of times
for Loops vs. while Loops
- while Loops: use when number of iterations is unknown
- for Loops: use when number of iterations is known
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
0
1
2
3
4
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
0
1
2
3
4
- Three parts in for loop header: variable initialization, Boolean (conditional) expression, and increment/decrement statement
Question: Which part is which?
- variable initialization (int i=0): sets variable before loop starts
- Boolean (conditional) expression (i < 5): defines condition for loop to run, in this case, the loop continues as long as i is less than 5, so loops 5 times i 05
- increment/decrement statement (i++): increases variable each time code block in the loop is executed, in this case it increases by 1
- variable can be used in the code block for other various reasons besides specifying how many times the loop will repeat
- Boolean (conditional) expression and increment/decrement statement together determine how many times the loop will repeat
4.3 Developing Algorithms Using Strings
LEARNING OBJECTIVES:
For algorithms in the context of a particular specification that involves String
objects:
- identify standard algorithms
- modify standard algorithms
- develop an algorithm
Java has many methods that are helpful when working with strings:
String .substring
–> retrieves portion of a stringString .equals
–> compares two stringsString .length
–> returns length of a stringfor Loop
–> iterating through characters of a string
Finding a substring within a string
We can use the “window” method:
A “window” is created the same length as the substring. We then iterate through the main string in sections and compare to the substring
For example:
I T E R A T E
with substring “ERA”
public class StringFinder {
public static void main(String[] args) {
String word = "iterate";
String sub = "rate";
boolean found = false; // will be set to true once substring is found
for (int i = 0; i <= word.length() - sub.length(); i++) { //iterating forwards: starting at first index (0) and going to the length of the word.. let's try word.length
String portion = word.substring(i, i + sub.length());
if (portion.equals(sub)) // make sure you use .equals!!
found = true;
}
if (found)
System.out.println("substring is found within string!");
else
System.out.println("substring is NOT within string");
}
}
StringFinder.main(null);
substring is found within string!
POPCORN HACK: Run the code.. what happened? How can we fix it?
The error stems from the for loop going until the length of the word even though the length of the word has an index that goes outside of the indexs of a word. To fix it we should change the for loop to instead have word.length - sub.length
Another Issue: What if our substring was the word “RATE”? Note that RATE is at the end of the whole string.
The code would not work as intended because it would stop at the first 'e' to fix this change it to <=
HACKS
**Create a algorithm similar to the one above. Except this time, use iteration to count the number of vowels within the main string.**
HINT: Use the boolean expressions we have learned in previous lessons. Which would you use when comparing your "window" with multiple options of substrings?
```java
public class VowelFinder {
public static void main(String[] args) {
String word = "supercalifrajilstiosus";
char[] arrayword = word.toCharArray();
char[] vowels = {'a','e','i','o','u'};
int num = 0;
boolean found = false;
for (int i = 0; i < word.length(); i++) {
for (int k = 0; k < vowels.length; k++) {
if (word.charAt(i) == vowels[k]) {
found = true;
num++;
}
}
}
if (found)
System.out.println(num+" vowels are in the string");
else
System.out.println(num+" vowels are not in the string");
}
}
VowelFinder.main(null);
```
vowels are in the string 9
# 4.4 Nested Iteration
**nested iteration**
occurs when we have a loop inside of another loop, similar to nested conditional statements in unit 3
When you have one loop inside another, the inner loop has to finish all its rounds before the outer loop moves to the next round. If the inner loop has a "stop" command, it only stops for that round of the outer loop. The next time the outer loop starts a new round, the inner loop starts over.
If you have two nested loops without stops, and the outer one runs n times while the inner one runs m times each time the outer one goes around, the inner loop will run m times n times, which is m * n times in total. This rule also applies if you have more than two nested loops. To find the total number of times the innermost loop runs, just multiply how many times each loop runs per round.
Another Issue: What if our substring was the word “RATE”? Note that RATE is at the end of the whole string.
The code would not work as intended because it would stop at the first 'e' to fix this change it to <=
HACKS
**Create a algorithm similar to the one above. Except this time, use iteration to count the number of vowels within the main string.**
HINT: Use the boolean expressions we have learned in previous lessons. Which would you use when comparing your "window" with multiple options of substrings?
```java
public class VowelFinder {
public static void main(String[] args) {
String word = "supercalifrajilstiosus";
char[] arrayword = word.toCharArray();
char[] vowels = {'a','e','i','o','u'};
int num = 0;
boolean found = false;
for (int i = 0; i < word.length(); i++) {
for (int k = 0; k < vowels.length; k++) {
if (word.charAt(i) == vowels[k]) {
found = true;
num++;
}
}
}
if (found)
System.out.println(num+" vowels are in the string");
else
System.out.println(num+" vowels are not in the string");
}
}
VowelFinder.main(null);
```
vowels are in the string 9
# 4.4 Nested Iteration
**nested iteration**
occurs when we have a loop inside of another loop, similar to nested conditional statements in unit 3
When you have one loop inside another, the inner loop has to finish all its rounds before the outer loop moves to the next round. If the inner loop has a "stop" command, it only stops for that round of the outer loop. The next time the outer loop starts a new round, the inner loop starts over.
If you have two nested loops without stops, and the outer one runs n times while the inner one runs m times each time the outer one goes around, the inner loop will run m times n times, which is m * n times in total. This rule also applies if you have more than two nested loops. To find the total number of times the innermost loop runs, just multiply how many times each loop runs per round.
HACKS
**Create a algorithm similar to the one above. Except this time, use iteration to count the number of vowels within the main string.** HINT: Use the boolean expressions we have learned in previous lessons. Which would you use when comparing your "window" with multiple options of substrings? ```java public class VowelFinder { public static void main(String[] args) { String word = "supercalifrajilstiosus"; char[] arrayword = word.toCharArray(); char[] vowels = {'a','e','i','o','u'}; int num = 0; boolean found = false; for (int i = 0; i < word.length(); i++) { for (int k = 0; k < vowels.length; k++) { if (word.charAt(i) == vowels[k]) { found = true; num++; } } } if (found) System.out.println(num+" vowels are in the string"); else System.out.println(num+" vowels are not in the string"); } } VowelFinder.main(null); ``` vowels are in the string 9 # 4.4 Nested Iteration **nested iteration**occurs when we have a loop inside of another loop, similar to nested conditional statements in unit 3
When you have one loop inside another, the inner loop has to finish all its rounds before the outer loop moves to the next round. If the inner loop has a "stop" command, it only stops for that round of the outer loop. The next time the outer loop starts a new round, the inner loop starts over.
If you have two nested loops without stops, and the outer one runs n times while the inner one runs m times each time the outer one goes around, the inner loop will run m times n times, which is m * n times in total. This rule also applies if you have more than two nested loops. To find the total number of times the innermost loop runs, just multiply how many times each loop runs per round.