About Lesson
1. Using a For Loop:
Problem: Print the numbers from 1 to 5.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
2. Using a While Loop:
Problem: Print the even numbers from 2 to 10.
let num = 2;
while (num <= 10) {
console.log(num);
num += 2;
}
3. Using a Do-While Loop:
Problem: Ask the user to guess a number between 1 and 5. Keep prompting them until they guess correctly.
let secretNumber = 3;
let guess;
do {
guess = parseInt(prompt("Guess the number (between 1 and 5):"));
} while (guess !== secretNumber);
alert("Congratulations! You guessed it!");
4. Using a For Loop:
Problem: Print the numbers from 10 to 1 in reverse order.
for (let i = 10; i >= 1; i--) {
console.log(i);
}
5. Using a While Loop:
Problem: Print the first 5 multiples of 3.
let num = 1;
let count = 0;
while (count < 5) {
if (num % 3 === 0) {
console.log(num);
count++;
}
num++;
}
6. Using a Do-While Loop:
Problem: Ask the user to enter a positive number. Keep prompting them until they enter a positive number greater than 10.
let userInput;
do {
userInput = parseInt(prompt("Enter a positive number greater than 10:"));
} while (isNaN(userInput) || userInput <= 10);
alert("Thank you!");
7. Using Nested For Loops:
Problem: Print a simple multiplication table for numbers 1 to 5.
for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= 5; j++) {
console.log(i + " x " + j + " = " + (i * j));
}
}
8. Using a For-In Loop (for Objects):
Problem: Iterate through the properties of an object and print them.
const person = {
name: "John",
age: 30,
city: "New York"
};
for (let key in person) {
console.log(key + ": " + person[key]);
}