13.3 For Loops and Nested Loops (15 mins)
Introduction to For Loops:
A
forloop is used to repeat a block of code a specific number of times. It’s ideal when you know how many iterations you want.Syntax:
for (initialization; condition; increment) { // Code to execute }Initialization: Typically used to declare and initialize a loop variable.
Condition: The loop runs as long as this condition is true.
Increment/Decrement: Updates the loop variable after each iteration.
Example: Loop through numbers 1 to 5:
for (let i = 1; i <= 5; i++) { console.log(i); // Outputs: 1, 2, 3, 4, 5 }
Nested For Loops:
A nested loop is a loop inside another loop. This is useful for iterating through multi-dimensional data (like arrays within arrays) or performing complex iterations.
Each time the outer loop runs once, the inner loop runs completely.
Syntax:
for (initialization; condition; increment) { for (initialization; condition; increment) { // Inner loop code } }Example: Using nested loops to print a 3x3 grid of numbers:
for (let i = 1; i <= 3; i++) { for (let j = 1; j <= 3; j++) { console.log("Row " + i + ", Column " + j); } }
Use Cases for Nested Loops:
Nested loops are commonly used for multi-dimensional arrays, matrices, or generating complex patterns.
Example of a Real-World Use Case: Looping through rows and columns of a table (like a multiplication table or grid).
Example: Printing a multiplication table:
for (let i = 1; i <= 5; i++) { for (let j = 1; j <= 5; j++) { console.log(i + " x " + j + " = " + (i * j)); } }Efficiency with Nested Loops:
Caution: Nested loops can become inefficient when working with large datasets because they significantly increase the number of iterations. Always try to minimize unnecessary iterations within loops.
forEach in JavaScript
The forEach() method in JavaScript is used to execute a provided function once for each array element. It is commonly used for iteration and performing actions on each array element
Syntax:
// Syntax for Foreach method
array.forEach(callback(element, index, arr), thisValue);// JavaScript
const arr = [1, 2, 3, 4, 5];
arr.forEach((item) => {
console.log(item);
});
// Output: 1 2 3 4 5Student Activity (15 mins):
Objective: Students will practice using basic for loops and nested loops to solve problems and understand how loops within loops can be used for more complex tasks.
Instructions:
Create an HTML file (e.g.,
for_nested_loops.html) and write JavaScript code that demonstrates both a basicforloop and nested loops.Example Code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>For Loops and Nested Loops</title> </head> <body> <h1>Check the Console for Loop Outputs</h1> <script> // Basic for loop: Print numbers 1 to 5 console.log("Basic For Loop:"); for (let i = 1; i <= 5; i++) { console.log(i); // Outputs: 1, 2, 3, 4, 5 } // Nested for loop: Print a 3x3 grid console.log("Nested For Loop (3x3 Grid):"); for (let i = 1; i <= 3; i++) { for (let j = 1; j <= 3; j++) { console.log("Row " + i + ", Column " + j); } } // Nested for loop: Multiplication table (1 to 5) console.log("Multiplication Table (1 to 5):"); for (let i = 1; i <= 5; i++) { for (let j = 1; j <= 5; j++) { console.log(i + " x " + j + " = " + (i * j)); } } </script> </body> </html>Run the file in a browser:
Open the HTML file in a browser and use Developer Tools (F12 or right-click and select Inspect > Console) to view the output of the loops.
Activity:
Step 1: Run the code and observe how the basic
forloop prints numbers and how the nested loops generate rows and columns.Step 2: Modify the loops:
Change the number of iterations in the
forloops to see how it affects the output (e.g., change the grid size to 4x4).Try reversing the loop condition (e.g., count down from 5 to 1).
Challenge:
Write a nested loop to print a triangle pattern with numbers:
for (let i = 1; i <= 5; i++) { let row = ''; for (let j = 1; j <= i; j++) { row += j + ' '; } console.log(row); // Outputs: 1, 1 2, 1 2 3, etc. }
Follow-up Questions:
What are the benefits of using nested loops when working with multi-dimensional data or complex structures?
How would you modify a nested loop to generate different patterns (e.g., grids, triangles)?
Can you think of any situations where nested loops might become inefficient?
Expected Outcome:
Students will understand the basic structure of a for loop and how nested loops work for more complex iterations. They will gain practical experience writing loops that generate multiple outputs and will be able to modify loop behavior to solve different problems.
Last updated