In this virtual lab, students will gain hands-on experience with for loops and nested loops. By engaging in interactive exercises, they will understand how loops can simplify repetitive tasks, manage complex iterations, and enhance their coding efficiency. This lab aims to demystify the iteration process, making it accessible and intuitive for all learners
Loops are fundamental constructs in programming that allow us
to execute a block of code repeatedly. They are essential for tasks that require iteration,
such as processing items in a list, generating sequences, or performing repetitive calculations.
For Loops
A for loop is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string).
The syntax is straightforward and allows for easy traversal of elements.
Nested For Loops
Nested loops are loops within loops.
They are useful for working with multi-dimensional data structures, such as lists of lists (matrices).
Benefits of Using Loops
- Efficiency: Loops reduce the need for repetitive code, making programs more efficient and easier to read.
- Automation They automate repetitive tasks, saving time and reducing the likelihood of errors.
- Flexibility: Loops can handle varying amounts of data, making them adaptable to different sceneriors.
- Initialization: The loop control variable is initialized (e.g., i = 0).
- Condition Check: The loop checks if the condition is true (e.g., i < 10). If true, it executes the loop body.
- Loop Body: The statements inside the loop are executed.
- Update: The loop control variable is updated (e.g., i += 1).
- Recheck Condition: The loop checks the condition again. If true, it repeats; if false, the loop terminates.


- Condition Check: The loop checks if the condition is true (e.g., i < 10). If true, it executes the loop body.
- Loop Body: The statements inside the loop are executed. The control variable should be updated inside the loop to ensure the condition eventually becomes false.
- Recheck Condition: After the loop body, the condition is checked again. If true, it repeats; if false, the loop terminates.
Example programs
let num = undefined;
let pattern = '';
for (let i = 0; i < num; i++) {
for (let j = 0; j < (num - i - 1); j++) {
pattern += ' '; // Add spaces
}
for (let k = 0; k < (2 * i + 1); k++) {
pattern += '* '; // Add stars
}
pattern += '\n';
}
2. Enter type of pattern:
i = , j = , k =
Current Pattern Value:
For Loop:
- The for loop is ideal when the number of iterations is known in advance. It runs a predefined number of times based on the range or condition set.
- It is easier to read and understand for repetitive tasks with a known range (e.g., printing a sequence of numbers).
- Geeks for Geeks
- W3 School
- Programiz
- pythonexamples.org
- Shiva Saini
- Vanilla HTML, CSS, JS - for creating the web page