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++;
}
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());
System.out.println(portion);
if (portion.equals(sub)){
// make sure you use .equals!!
found = true;
break;
}
}
if (found)
System.out.println("substring is found within string!");
else
System.out.println("substring is NOT within string");
}
}
StringFinder.main(null);
iter
tera
erat
rate
substring is found within string!
POPCORN HACK: Run the code.. what happened? How can we fix it?
There was initially an error that said that the index was out of range, which I was able to fix temporarily by making the code loop from 0 to word.length()-1. The issue still was that the code did not recognize the fact that the substring “iter” was actually in the string. In order to fix that, we made it so that the for loop went from i = 0 to the length of the word minus the length of the substring. When we did this, the code correctly identified “iter” to be in the string. The one problem that also arose, however, was that this only worked for that substring, so in order to make it work for any of the substrings, we made the for loop go up to and including the difference between the word length and the substring length and adding a break statement so that it would end the loop at the correct character.
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
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?
Vowels
import java.util.Scanner;
public class VowelCount {
public static void main(String [] args){
String test = "happy birthday emu";
char[] c = test.toCharArray();
int vowels = 0;
for(int i = 0; i < test.length(); i++){
if(test.charAt(i) == 'a' || test.charAt(i) == 'e' || test.charAt(i) == 'i' || test.charAt(i) == 'o' || test.charAt(i) == 'u'){
vowels++;
}
}
System.out.println(vowels);
}
}
VowelCount.main(null);
5
Calculate and print the sum of all even numbers from 1 to a given positive integer ‘n’ (user input n)
public class EvenSum {
public static void main(String [] args){
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter any number that you would like for the maximum value: ");
int n = sc.nextInt();
System.out.printf("Your number: %d%n",n);
for(int i = 0; i < n; i+=2){
sum += i;
}
System.out.println(sum);
}
}
EvenSum.main(null);
Enter any number that you would like for the maximum value:
Your number: 22
110
4.4 Nested Iteration
nested iteration
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.
public class NestedLoopsDemo {
public static void main(String[] args) {
int n = 3; //numb of times the outside loop runs
int m = 2; //numb of times the inside loop runs
//the nested loops
for (int i = 1; i <= n; i++) {
System.out.println("Outer loop iteration: " + i);
for (int j = 1; j <= m; j++) {
System.out.println("Inner loop iteration: " + j);
}
}
}
}
NestedLoopsDemo.main(null)
Outer loop iteration: 1
Inner loop iteration: 1
Inner loop iteration: 2
Outer loop iteration: 2
Inner loop iteration: 1
Inner loop iteration: 2
Outer loop iteration: 3
Inner loop iteration: 1
Inner loop iteration: 2
Break Statement
break statement
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.println("Outer loop iteration " + i);
for (int j = 1; j <= 3; j++) {
System.out.println("Inner loop iteration " + j);
if (i == 2 && j == 2) {
System.out.println("Breaking inner loop");
break; //break out of the inside loop when i is 2 and j is 2.
}
}
}
}
}
BreakExample.main(null)
Outer loop iteration 1
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3
Outer loop iteration 2
Inner loop iteration 1
Inner loop iteration 2
Breaking inner loop
Outer loop iteration 3
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3
Popcorn HACK
When the targetNumber is found, you can print a message and use the break statement to exit the loop. When it’s not found, you can print a message indicating that the number was not found.
public class BreakHack {
public static void main(String[] args) {
int targetNumber = 42; //numb we want
int[] numbers = {10, 20, 30, 40, 50, 60, 70}; //numb array
for (int number : numbers) {
if (number == targetNumber) {
System.out.println("Number was found!");
break;
} else {
System.out.println("Number was not found!");
break;
}
}
//if numb isnt found
//print message showing numb wasnt found if you want
}
}
BreakHack.main(null);
Number was not found!
Continue Statement
continue statement
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.println("Outer loop iteration " + i);
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
System.out.println("Skipping inner loop iteration " + j);
continue; //skip the iteration when i is 2 and j is 2.
}
System.out.println("Inner loop iteration " + j);
}
}
}
}
ContinueExample.main(null)
Outer loop iteration 1
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3
Outer loop iteration 2
Inner loop iteration 1
Skipping inner loop iteration 2
Inner loop iteration 3
Outer loop iteration 3
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3
Patterns and Shapes
import java.util.Scanner;
public class InteractivePyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the symbol you want to use: ");
char symbol = scanner.next().charAt(0);
System.out.print("Enter the number of rows for the pyramid: ");
int numRows = scanner.nextInt();
for (int i = 1; i <= numRows; i++) {
//print space before the symbol
for (int j = 1; j <= numRows - i; j++) {
System.out.print(" ");
}
//print
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print(symbol);
}
System.out.println(); //next line
}
scanner.close();
}
}
InteractivePyramid.main(null)
Enter the symbol you want to use: Enter the number of rows for the pyramid: ^
^^^
^^^^^
Hacks
- Modify pyramid code:
- Create different patterns (other then pyramid) by modifying nested loop structure
- Questions
- What is a nested iteration, continue statement, and break statement (in your own words)?
Nested iterations: iteration statements that appear within the body of another iteration statement. When a loop is “nested” within another loop, the inner loop must complete all of its iterations before the outer loop can continue.
Continue statement: continue statements are used to skip the current iteration of a loop.
Break statement: A statement that ends a for or while loop so that they do not execute forever.
- Create a simple example of a continue statement or break statement
// instead of a pyramid, I created a rectangular pattern. the user can make the length and width whatever they want and see how their rectangle looks at the end using the character they chose
import java.util.Scanner;
public class RectangularPattern {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the symbol you want to use for the rectangle: ");
char symbol = scanner.next().charAt(0);
System.out.print("Enter the number of rows for the rectangle:\n ");
int numRows = scanner.nextInt();
System.out.print("Enter the number of columns for the rectangle: ");
int numColumns = scanner.nextInt();
System.out.println();
for (int i = 1; i <= numRows; i++) {
for (int j = 1; j <= numColumns; j++) {
System.out.print(symbol);
}
System.out.println(); // Move to the next line
}
scanner.close();
}
}
RectangularPattern.main(null);
Enter the symbol you want to use:
Enter the number of rows:
Enter the number of columns:
UUUUUU
UUUUUU
UUUUUU
UUUUUU
UUUUUU
UUUUUU
UUUUUU
UUUUUU
UUUUUU
UUUUUU
UUUUUU
UUUUUU
Continue Statement (Hacks)
public class ContinueHomework {
public static void main(String [] args){
for(int i = 0; i < 10; i++){
if(i == 4){
System.out.println("Skip 4");
continue;
}
System.out.println((double)1/(i-4));
}
}
}
ContinueHomework.main(null);
-0.25
-0.3333333333333333
-0.5
-1.0
Skip 4
1.0
0.5
0.3333333333333333
0.25
0.2
Break Statement (Hacks)
public class BreakHomework {
public static void main(String [] args){
int [] numbers = {7, 17, 31, 60, 70, 74, 76, 83, 89, 97};
for(int i = 0; i < numbers.length; i++){
if(numbers[i] >= 75){
System.out.println("stopped iterating through the array");
break;
}
System.out.println(numbers[i]);
}
}
}
BreakHomework.main(null);
7
17
31
60
70
74
stopped iterating through the array
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: Computing the informal run time based on the number of times a statement is executed.
// 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 times
How many times will statement 2 execute?
Answer: 10 times
// 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
}
}
}
How many times will statement 3 execute?
Answer: 9 times
// Rewrite the code segment below to have a faster run-time based on statement execution counts
for (int k = 0; k < 135; k+=5)
{
if (k % 5 == 0)
{
System.out.println(k);
}
}
0
5
10
15
20
25
30
35
40
45
50
55
60
65
70
75
80
85
90
95
100
105
110
115
120
125
130
// CODE EXAMPLE #3 (while loop)
int num = (int)(Math.random() * 10);
while (num % 2 != 0)
{
num = (int)(Math.random() * 10); // statement 4
}
What is the min/max number of times statement 4 will execute?
Answer: min num = 0, max num = unknown, could always generate a number not divisible by 2
// 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 (3*4)
// 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: We don’t know, as how many times the statement will execute depends on what number x is randomly generated.
4.5 Hacks
#1 How many times will statement #1 and statement #2 execute in the code segments below?
for (int k = 0; k < 1000; k++)
{
// statement #1
}
// statement 1 will execute 1000 times
for (int k = 6; k < 50; k++)
{
// statement #2
}
// statement 2 will execute 45 times
#2 How many times will statement #3 execute for the code segment below?
28 times (7*4).
int k = 1;
while (k <=7)
{
for (int z = 0; z < 4; z++)
{
System.out.println("hello");
}
k++;
}
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
#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
// 3a code
for(int i = 0; i < 100; i+=10){
if(i % 10 == 0){
System.out.println(i);
}
}
0
10
20
30
40
50
60
70
80
90
// 3b code
int i = 0;
while(i < 10){
System.out.println("I love Java!");
i++;
}
I love Java!
I love Java!
I love Java!
I love Java!
I love Java!
I love Java!
I love Java!
I love Java!
I love Java!
I love Java!
// 3c code
for(int i = 0; i < 2; i++){
for (int j = 0; j < 5; j++){
System.out.println("Code Code Code!");
}
}
Code Code Code!
Code Code Code!
Code Code Code!
Code Code Code!
Code Code Code!
Code Code Code!
Code Code Code!
Code Code Code!
Code Code Code!
Code Code Code!