-
Notifications
You must be signed in to change notification settings - Fork 0
/
day4.js
157 lines (126 loc) · 2.16 KB
/
day4.js
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
// Activity 1: For Loop
// Task 1: Write a program to print numbers from 1 to 10 using a for loop.
for (let i = 1; i <= 10; i++) {
const element = i;
console.log(element);
}
//Outputs
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// 10
// Task 2: Write a program to print the multiplication table of 5 using a for loop.
let n = 5;
for (let i = 1; i <= 10; i++) {
console.log(n + '*' + i + '=' + n*i);
}
// Outputs
// 5*1=5
// 5*2=10
// 5*3=15
// 5*4=20
// 5*5=25
// 5*6=30
// 5*7=35
// 5*8=40
// 5*9=45
// 5*10=50
// Activity 2: While Loop
// Task 3: Write a program to calculate the sum of numbers from 1 to n using a while loop.
let i = 0,sum = 0;
while (i<100) {
sum = sum + i;
i++;
}
console.log(sum); //Output: 4950
// Task 4: Write a program to print numbers from 10 to 1 using a while loop.
let x = 10;
while (x>0) {
console.log(x);
x--;
}
//Outputs:
// 10
// 9
// 8
// 7
// 6
// 5
// 4
// 3
// 2
// 1
// Activity 3: Do…While Loop
// Task 5: Write a program to print numbers from 1 to 5 using a do…while loop.
let y = 1;
do {
console.log(y);
y++;
} while (y<=5);
// Outputs:
// 1
// 2
// 3
// 4
// 5
// Task 6: Write a program to calculate the factorial of a number using a do…while loop.
let z = 1,fact = 1;
do {
fact = fact * z;
z++;
} while (z<=5);
console.log(fact); //Output: 120
// Activity 4: Nested Loops
// Task 7: Write a program to print a pattern using nested for loops.
let pattern = "";
for (let i = 0; i < 5; i++) {
for (let j = 0; j <= i; j++) {
pattern += "*";
}
pattern += "\n";
}
console.log(pattern);
// Outputs:
// *
// **
// ***
// ****
// *****
// Activity 5: Loop Control Statements
// Task 8: Write a program to print numbers from 1 to 10, but skip the number 5 using the continue statement.
for (let a = 1; a <= 10; a++) {
if (a == 5) {
continue;
}
console.log(a);
}
// Outputs:
// 1
// 2
// 3
// 4
// 6
// 7
// 8
// 9
// 10
// Task 9: Write a program to print numbers from 1 to 10, but stop the loop when the number is 7 using the break statement.
for (let b = 1; b < 10; b++) {
if (b === 7) {
break;
}
console.log(b);
}
// Output:
// 1
// 2
// 3
// 4
// 5
// 6