-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path021-do-while.js
More file actions
79 lines (56 loc) · 1.55 KB
/
021-do-while.js
File metadata and controls
79 lines (56 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// 1: WHAT IS A DO WHILE LOOP?
// do {
// // code to be executed
// } while (condition);
// 2: DO WHILE VS WHILE LOOP
// let count = 5;
// while (count < 3) {
// console.log("Count is: " + count);
// count++;
// }
// console.log("Loop finished");
let count = 5;
do {
console.log("Count is: " + count);
count++;
} while (count < 3);
console.log("Loop finished");
// 3: PRACTICAL EXAMPLES
// Example 1: User Input Validation
let userInput;
do {
userInput = prompt("Please enter a number between 1 and 10:");
userInput = Number(userInput);
} while (userInput < 1 || userInput > 10 || isNaN(userInput));
console.log("Thank you! You entered: " + userInput);
// Example 2: Menu Systems
let choice;
do {
console.log("=== Menu ===");
console.log("1. Start Game");
console.log("2. Settings");
console.log("3. Exit");
choice = prompt("Enter your choice (1-3):");
if (choice === "1") {
console.log("Starting game...");
} else if (choice === "2") {
console.log("Opening settings...");
}
} while (choice !== "3");
console.log("Thanks for playing!");
// 4: COMMON PATTERNS & BEST PRACTICES
// let i = 1;
// do {
// console.log("Iteration: " + i);
// i++;
// } while (i <= 5);
// BAD - Infinite loop!
// let x = 0;
// do {
// console.log(x);
// // Forgot to increment x!
// } while (x < 5);
do {
console.log("Hello");
} while (false); // Semicolon is required here!
// 5: WHEN TO USE DO WHILE