Unit 4 Iteration
Homework for Unit 4: Iteration
int i = 0;
do {
System.out.println("i is: " + i);
i++;
}while (i < 0);
Compare the code above with the while loop below:
int i = 0;
while (i < 0) {
System.out.println("i is: " + i); // no output
}
Notes
for loops
For loops help with iteration. With for loops, you can specify how many times you want to repeat through something.
The syntax is: for (1; 2; 3){}
(numbers explained below)
- 1: Initialize a variable and set it equal to a certain value
- 2: Create a conditional with the variable in 1
- 3: Set an increment for the variable
Putting it all together, a for loop might look like this:
for (int i = 1; i <= 5; i++) {
System.out.println("The value of i is: " + i);
}
int[] num = {1, 2, 3};
for (int numbers : num) {
System.out.println(numbers);
}
while loops
The syntax of a while loop looks like this:
while (condition) {
}
Everytime the while loop executes, it first checks the condition. If the condition is true, the code inside the loop is ran. After the code finishes, the while loop checks again with the condition.
for loops
The syntax of a for loop looks like this:
for (initialize variable; condition; change variable) {
}
Every time the for loop executes, it checks the condition. If the condition is true, the code inside the for loop is ran. After the code finishes running, the variable is incremented by the amount specified.
There can also be nested iteration (ex: for loop within for loop)
for each loop
The syntax for a for-each loop looks like this:
for (dataType item : array){
}
This is especially useful for iterating through arrays.
public class CaesarCipher {
String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
String[] capitalLetters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
static String message1 = "Kfzb gly!";
static String message2 = "zlab zlab zlab";
static String message3 = "prmbozxifcoxdfifpqfzbumfxifalzflrp";
String letterIndividual = "";
public CaesarCipher(String msg) {
for (int i = 0; i < msg.length(); i++) {
letterIndividual = msg.substring(i, i+1);
if (letterIndividual.equals(" ")) {
System.out.print(" ");
}
if (letterIndividual.equals("!")) {
System.out.print("!");
}
for (int j = 0; j < letters.length; j++) {
if (letterIndividual.equals(letters[j])) {
System.out.print(letters[(j+3)%26]);
}
if (letterIndividual.equals(capitalLetters[j])) {
System.out.print(capitalLetters[(j+3)%26]);
}
}
}
System.out.println("");
}
public static void main(String[] args) {
CaesarCipher decode = new CaesarCipher(message1);
CaesarCipher decode2 = new CaesarCipher(message2);
CaesarCipher decode3 = new CaesarCipher(message3);
}
}
CaesarCipher.main(null)