Hard Prerequisites |
IMPORTANT: Please review these prerequisites, they include important information that will help you with this content. |
|
In this section, we will explore loops, which are essential programming structures that allow you to repeat a set of instructions multiple times. Loops help automate repetitive tasks and make your code more efficient. Understanding how to work with different types of loops—such as while loops, iterating loops, and nested loops—is crucial for writing effective code that can handle large datasets or repeated operations.
Applied Knowledge
By completing this section, you will gain an understanding of:
Given a problem statement and access to a suitable PC or device with software toolkit/platform, the learner must be able to:
While Loop
while
loop repeats a block of code as long as a specified condition is true
.false
to prevent an infinite loop.Syntax:
while (condition) {
// code to be executed
}
Example:
let count = 1;
while (count <= 5) {
console.log(count);
count++; // Increment count
}
// Output:
// 1
// 2
// 3
// 4
// 5
In this example, the loop continues to execute as long as count is less than or equal to 5. After each iteration, the value of count increases by 1.
Iterating Loops (For Loops)
for
is commonly used when the number of iterations is known. It’s structured with three parts: initialization, condition, and iterator.Syntax:
for (initializer; condition; iterator) {
// code to be executed
}
Example:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output:
// 1
// 2
// 3
// 4
// 5
In this case, the loop starts by initializing i
to 1, checks the condition (i <= 5
), and increments i after each iteration. The loop stops when the condition evaluates to false
.
Nested Loops
Syntax:
for (let i = 0; i < rows; i++) {
for (let j = 0; j < columns; j++) {
// code to be executed
}
}
Example:
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`Row ${i}, Column ${j}`);
}
}
// Output:
// Row 1, Column 1
// Row 1, Column 2
// Row 1, Column 3
// Row 2, Column 1
// Row 2, Column 2
// Row 2, Column 3
// Row 3, Column 1
// Row 3, Column 2
// Row 3, Column 3
In this example, the outer loop runs three times, and for each iteration, the inner loop runs three times as well, resulting in a total of nine outputs.
Your supervisor, facilitator, or mentor will assess you based on the following:
Task:
Write a program that prints the multiplication table for a number (e.g., 5) using a loop.
let number = 5;
for (let i = 1; i <= 10; i++) {
console.log(`${number} x ${i} = ${number * i}`);
}
//5 x 1 = 5
//5 x 2 = 10
//...
//5 x 10 = 50
By completing this section, you will have developed a clear understanding of how to code loops, use them effectively, and ensure your code is both efficient and easy to maintain.