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++;
}
}
}
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++;
}
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
- 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
Calculate and print the sum of all even numbers from 1 to a given positive integer ‘n’ (user input n)
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int ans = 0;
for (int i = 2; i <= n; i += 2)
{
ans += i;
}
System.out.println(ans);
}
main(null);
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 = "era";
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);
POPCORN HACK: Run the code.. what happened? How can we fix it?
Tell us below!
The iterations in the for loop should be word.length - sub.length because the substring window is going over by two extra characters
Another issue:
I T E R A T E
What if our substring was the word “RATE”? Note that RATE is at the end of the whole string
The loop ends early because word.length - sub.length stops the loop at the first e, set it to <= instead.
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?
public class Vowels {
public static void main(String[] args) {
int vowelCount = 0;
String string = "wpfkvmvrugtdovnkltpcvorjekio";
for (int i=0; i< string.length(); i++) {
char current = string.charAt(i);
if (current == 'a' || current == 'e' || current == 'i' || current == 'o' || current == 'u') {
vowelCount++;
}
}
System.out.println(vowelCount);
}
}
Vowels.main(null);
6
4.4 Nested Iteration
nested iteration
A nested iteration is a loop inside another loop. Continue means to skip to the next iteration of the loop. Break stops the loops. - Create a simple example of a continue statement **or** break statement ```java for (int i = 0; i < 100; i++) { if (i == 7) { break; } } ``` --- # 4.5 Informal Code Analysis Learning objective: Compute statement execution counts & informal run-time comparison of iterative statements Essential Knowledge: A statement execution count indicates the number of times a statement is executed by the program
What IS informal code analysis?
Answer: the theoretical max runtime of the code ```java // CODE EXAMPLE #1 (for loop) public class InformalCodeAnalysis { public static void main(String[] args) { int count = 0; for (int k = 0; k < 30; k++) { if (k % 3 == 0) // statement 1 { count++; // statement 2 } } } } ``` How many times will statement 1 execute? Answer: 30 How many times will statement 2 execute? Answer: 10 ```java // CODE EXAMPLE #2 (for loop) public class InformalCodeAnalysis { public static void main(String[] args) { int count = 0; for (int k = 4; k < 30; k+=3) { count++; // statement 3 } System.out.println(count); } } InformalCodeAnalysis.main(null); ``` How many times will statement 3 execute? Answer: 8 ```java // CODE EXAMPLE #3 (while loop) int num = (int)(Math.random() * 10); while (num % 2 != 0) { num = (int)(Math.random() * 10); // statement 4 } ``` ```java // Rewrite the code segment below to have a faster run-time based on statement execution counts for (int k = 0; k < 135; k+=5) { System.out.println(k); } ``` What is the min/max number of times statement 4 will execute? Answer: min: 0, no theoretical max ```java // CODE EXAMPLE #4 (nested loop) for (int outer = 0; outer < 3; outer++) { for (int inner = 0; inner < 4; inner++) { // statement #5 } } ``` How many times will statement #5 execute? Answer: 12 ```java // CODE EXAMPLE #5 (nested loop) int k = 0; while (k < 5) { int x = (int)(Math.random() * 6) + 1; while (x != 6) { // statement #6 x = (int)(Math.random() * 6) + 1; } k++; } ``` How many times will statement #6 execute? Answer: unknown, the random function could never be divisible by 6 # 4.5 Hacks #1 How many times will statement #1 and statement #2 execute in the code segments below?1: 1000, 2: 44 ```java for (int k = 0; k < 1000; k++) { // statement #1 } ``` ```java for (int k = 6; k < 50; k++) { // statement #2 } ``` #2 How many times will statement #3 execute for the code segment below?
28 ```java int k = 1; while (k <=7) { for (int z = 0; z < 4; z++) { // statement #3 } k++; } ``` #3 Create 3 seperate code segments that execute a statement 10 times using: (a) a for loop (b) a while loop (c) a nested loop ```java // 3a code for (int i = 0; i < 10; i++) { System.out.println("I refuse"); } ``` ```java // 3b code int i = 0 while (i < 10) { System.out.println("I refuse"); i++; } ``` ```java // 3c code for (int i = 0; i < 5; i++) { for (int j = 0; j < 2; j++) { System.out.println("I refuse"); } } ```