Iteration lesson
Week 1 College Board Lessons
Iterations Notes
4.1 While Loops
- Repeat code while boolean expression evaluates to true
while (condition) { // code to run }
- While loops are useful to iterate over arrays ``` int[] array = {1, 2, 3, 4} int total = 0; int i = 9;
while(i < array.length) { total += array[i]; i++; }
System.out.println(total);
- Infinite while loops run over and over again, since the condition is always true; useful for user input
while(true) { System.out.println("Choose an option"); } ```
public class WhileLoops {
public static void main(String[] args) {
int profit = 5450000;
int i = 0;
while(profit < 30000000) {
profit *= 1.05;
i++;
}
System.out.println(i);
}
}
WhileLoops.main(null);
public class ForLoops {
public static void main(String[] args) {
for(int i = 10; i<= 15; i++) {
System.out.println(i);
}
int[] temperatures = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for(int i = 0; i<temperatures.length; i++) {
System.out.println(temperatures[i] + 273);
}
}
}
ForLoops.main(null);
public class ForEachLoops {
public static void main(String[] args) {
int[] data = {2, 10, 5, 12};
for(int number: data) {
System.out.println(number);
}
}
}
ForEachLoops.main(null);
int numbers[] = {2, 5, 7, 12};
int total = 0;
for(int number: numbers) {
total += number;
}
System.out.println(total);
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"};
public String cipher(String message) {
String encodedMessage = "";
for(int i = 0; i<= message.length; i++) {
int newLetter = ArrayUntils.indexOf(letters, message[i]);
}
}
public static void main(String[] args) {
String message1 = "Kfzb gly!";
String message2 = "zlab zlab zlab";
String message3 = "prmbozxifcoxdfifpqfzbumfxifalzflrp";
}
}
CaesarCipher.main(null);