Loops
Topic: Control Flow (Extended)
Concepts Covered:for,while,break,continue
Why Use Loops?
Section titled “Why Use Loops?”Loops allow us to repeat actions efficiently instead of writing repetitive code:
- Log numbers from 1 to 200
- Keep asking for user input until valid
- Generate multiplication tables
- Process repetitive calculations
While Loops
Section titled “While Loops”The while loop executes code as long as a condition is true:
Basic While Loop
Section titled “Basic While Loop”// Syntaxwhile (condition) { // Code to execute // Don't forget to update the condition!}Examples
Section titled “Examples”Simple Counter
Section titled “Simple Counter”let count = 0;
while (count < 5) { console.log(`Number: ${count}`); count = count + 1; // or count++}// Output: Number: 0, Number: 1, Number: 2, Number: 3, Number: 4Multiplication Table
Section titled “Multiplication Table”let multiplier = 1;
while (multiplier <= 12) { console.log(`4 x ${multiplier} = ${4 * multiplier}`); multiplier += 1;}Password Checker with Attempts
Section titled “Password Checker with Attempts”const correct_password = "test123";let input = prompt("Input your password");let user_attempt = 0;
while (input !== correct_password) { user_attempt += 1;
if (user_attempt === 3) { alert("Try again after 3 minutes"); break; // Exit the loop }
input = prompt("Wrong password, Input correct password");}
if (input === correct_password) { alert("Correct password!!");}For Loops
Section titled “For Loops”The for loop is used when you know how many times you want to repeat:
Basic For Loop
Section titled “Basic For Loop”// Syntaxfor (initial value; condition; increment/decrement) { // Code to execute}Examples
Section titled “Examples”Multiplication Table
Section titled “Multiplication Table”for (let i = 1; i <= 12; i++) { console.log(`6 x ${i} = ${6 * i}`);}Sum Calculator
Section titled “Sum Calculator”let input = +prompt("Input a number");let sum = 0;
for (let i = 1; i <= input; i++) { sum += i;}
console.log(`Sum from 1 to ${input} = ${sum}`);Reverse Numbers
Section titled “Reverse Numbers”let input = +prompt("Input a number");
for (let i = input; i > 0; i--) { console.log(i);}Loop Control Statements
Section titled “Loop Control Statements”Exits the loop completely:
for (let i = 1; i <= 10; i++) { if (i === 5) { break; // Exit when i equals 5 } console.log(i);}// Output: 1, 2, 3, 4Continue
Section titled “Continue”Skips the current iteration and continues with the next:
for (let i = 1; i <= 10; i++) { if (i % 2 === 0) { continue; // Skip even numbers } console.log(i);}// Output: 1, 3, 5, 7, 9Common Loop Patterns
Section titled “Common Loop Patterns”Range Even Numbers
Section titled “Range Even Numbers”let start = +prompt("Enter start number");let end = +prompt("Enter end number");
let current = start;while (current <= end) { if (current % 2 === 0) { console.log(current); } current++;}FizzBuzz
Section titled “FizzBuzz”for (let i = 1; i <= 100; i++) { if (i % 3 === 0 && i % 5 === 0) { console.log("FizzBuzz"); } else if (i % 3 === 0) { console.log("Fizz"); } else if (i % 5 === 0) { console.log("Buzz"); } else { console.log(i); }}When to Use Which Loop
Section titled “When to Use Which Loop”Use for when:
Section titled “Use for when:”- You know the exact number of iterations
- Working with counters or ranges
- Need the index value
Use while when:
Section titled “Use while when:”- The number of iterations is unknown
- Looping until a condition is met
- Processing user input until valid
Common Pitfalls
Section titled “Common Pitfalls”Infinite Loops
Section titled “Infinite Loops”Always ensure your loop condition will eventually become false:
// ❌ Infinite loop - counter never changeslet counter = 20;while (counter > 0) { console.log(`Number: ${counter}`); // Missing: counter--;}
// ✅ Fixed versionlet counter = 20;while (counter > 0) { console.log(`Number: ${counter}`); counter--; // or counter = counter - 1;}Off-by-One Errors
Section titled “Off-by-One Errors”Be careful with your loop conditions:
// Common mistake - stopping too earlyfor (let i = 1; i < 10; i++) { console.log(i); // This only goes to 9, not 10!}
// Correct version - if you want 1 through 10for (let i = 1; i <= 10; i++) { console.log(i); // This goes from 1 to 10}Best Practices
Section titled “Best Practices”- Use meaningful variable names:
i,j,kfor simple counters, descriptive names for complex loops - Avoid modifying loop variables inside the loop body (for
forloops) - Always ensure the loop will terminate to avoid infinite loops
- Use
breakandcontinuesparingly and only when they make code clearer - Choose the appropriate loop type for your specific use case
Key Takeaways
Section titled “Key Takeaways”whileloops are condition-based,forloops are count-based- Always ensure your loops will terminate to avoid infinite loops
- Use
breakto exit early,continueto skip iterations - Choose the right loop type for your specific use case
- Be careful with loop conditions to avoid off-by-one errors
Practice Exercises
Section titled “Practice Exercises”- Write a program that finds all prime numbers between 1 and 100
- Create a guessing game where the user has limited attempts
- Build a multiplication table generator for any number
- Write a program that reverses a string using loops
- Create a program that counts vowels in a sentence