Skip to content

Commit d7b0349

Browse files
committed
break continue with DSA
1 parent bde4533 commit d7b0349

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

Array1.html

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<title>Array Exercise</title>
5+
</head>
6+
<body>
7+
<script>
8+
/* Create a while loop that exits after counting 5 prime numbers & Modify the above loop to finish using break */
9+
10+
function isPrime(num) {
11+
if (num <= 1) return false;
12+
13+
//for (let i = 2; i < num; i++) here need check 2 to 99
14+
15+
// but here, √100 = 10; so check 2 to 10
16+
// √29 = 5.38; check 2, 3, 4, 5...don't need check 2 to 28
17+
18+
for (let i = 2; i <= Math.sqrt(num); i++) {
19+
if (num % i === 0) {
20+
return false;
21+
}
22+
}
23+
return true;
24+
}
25+
26+
console.log(isPrime(100));
27+
console.log(isPrime(29));
28+
29+
let num = 2;
30+
let i = 0;
31+
32+
while (true) {
33+
if (isPrime(num)) {
34+
// if true, print and increase i
35+
console.log(num);
36+
i++;
37+
38+
if (i >= 10) {
39+
break;
40+
41+
// num++; Only increment if prime
42+
}
43+
}
44+
num++; // Increment if not prime
45+
}
46+
47+
// while (i < 5) {
48+
// if (isPrime(num)) {
49+
// console.log(num);
50+
// i++;
51+
// }
52+
// num++;
53+
// }
54+
55+
/* Using continue only print positive numbers from the given array [1, -6, 5, 7, -98] */
56+
57+
let nums = [1, -6, 5, 7, -98];
58+
59+
for (let i = 0; i < nums.length; i++) {
60+
if (nums[i] < 0) continue;
61+
62+
console.log(nums[i]);
63+
}
64+
65+
/* Using accumulator pattern concatenate all the strings in the given array ['Deep', 'Coding', 'JavaScript', 'Course', 'Is', 'Best'] */
66+
67+
let arr = ["Deep", "Coding", "JavaScript", "Course", "Is", "Best"];
68+
69+
let result = "";
70+
for (let i = 0; i < arr.length; i++) {
71+
result += arr[i] + " -";
72+
}
73+
74+
console.log(result); // Deep - Coding - JavaScript - Course - Is - Best -
75+
76+
console.log(arr.join("")); //DeepCodingJavaScriptCourseIsBest
77+
78+
console.log(arr.join(",")); // Deep,Coding,JavaScript,Course,Is,Best
79+
80+
console.log(arr.join(" ")); //Deep Coding JavaScript Course Is Best
81+
</script>
82+
</body>
83+
</html>

0 commit comments

Comments
 (0)