Unit 6 | 6.1 Array | 6.2 Traversing | 6.3 Enhanced for | 6.4 Algos |
Unit 6.3 Lesson
- Enhanced For Loop (For-each)
- Regular For Loop
- Enhanced For Loop
- Comparing a regular for loop with the enhanced for loop
- Hacks
Enhanced For Loop (For-each)
An enhanced For Loop is a simplified version of a regular for loop, where the coder doesn’t need to specify the increment and can access each element directly.
Pros
- Can access the elements of a array instad of a counter
- Enhanced readability
- Less likely to be buggy
Cons
- Can only traverse the array in order
- Accesses a copy of the array, so modifications to the variables are not saved in the original array
Regular For Loop
Enhanced For Loop
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
number += 1;
System.out.println(number);
};
System.out.println(Arrays.toString(numbers))
Comparing a regular for loop with the enhanced for loop
Popcorn Hack: Rewrite this code to use an enhanced for loop instead. make comments explaining what you added/changed
String[] languages = {"Java", "Python", "Markdown", "C++", "Go", "JavaScript", "HTML"};
for (int i = 0; i<languages.length; i++) {
System.out.println(languages[i]);
};
Hacks
- Build the loop
- Multiple Choice
- Find each index of the letter ‘a’ in each word
- Find the error
- HW Hack
String[] myArray = {'Add an array here'};
// Add a loop to go through the array here
private String[] myArray = {
"And", "Table", "Shirts", "Tea", "School Day"
};
for (String currentWord : myArray) {
// Add code here
}
A: System.out.println(myArray.currentWord.length());
B: System.out.println(myArray[index].length());
C: System.out.println(myArray[currentWord].length());
D: System.out.println(currentWord.length());
String[] fruits = {"Apple", "Banana", "Orange"};
for (String fruit: fruits) {
// Find the index of the letter 'a' in each fruit
};
String[] myArray = {"Object 1", "Object 2", "Object 3", "Object 4", "Object 5"};
for (currentWord: myArray) {
System.out(currentWord)
};
// There are 3 errors, can you find them?
Final Hack
Add to the code below to create a average grade calculator (using an enhanced for loop)
Integer[] grades = {88, 93, 55, 68, 77};
Scanner userGrades = new Scanner(System.in);
System.out.print("Enter a grade: ");
int grade = Integer.parseInt(userGrades.nextLine());
// Add code here to take the average
grades = Arrays.copyOf(grades, grades.length + 1);
grades[grades.length - 1] = grade;
System.out.println(Arrays.toString(grades));