-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfor - while.js
More file actions
146 lines (107 loc) · 2.04 KB
/
Copy pathfor - while.js
File metadata and controls
146 lines (107 loc) · 2.04 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
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
FOR LOOP
1.Write a program to print numbers from 1 to 5 using a loop.
for (let i =1; i<=5; i++){
console.log(i)
}
2.Find the sum of numbers from 1 to 10.
var sum = 0
for (let i =1; i<=10; i++){
sum+=i
}
console.log(sum)
3. Print even numbers from 1 to 20
for (let i=1; i<=20; i++){
if (i%2===0){
console.log(i)
}
}
4. Reverse a number
let num = 12345
let rev = 0
while (num>0){
let digit = num % 10
rev = rev*10+digit;
num = Math.floor(num/10)
}
console.log(rev)
built-in
let rev= +num.toString().split('').reverse().join('');
console.log(rev).
5. Count digits in a number
let num = 987654
let count = 0
while(num>0){
count++
num = Math.floor(num/10)
}
console.log(count)
6. Print elements of an array
let num =[12,34,56,67,90]
for (let i =0; i<=num.length; i++){
console.log(num[i])
}
7. Find largest number in an array
let num =[4,65,6,7,87,90]
let max = num[0]
for (let i=1; i<num.length; i++){
if(num[i]>max){
max =num[i]
}
}
console.log(max)
8. Pattern printing (important 🔥)
for(let i=1; i<=4;i++){
let star="";
for (let j=1; j<=i; j++){
star+='*'
}
console.log(star)
}
9. Break statement
for (let i=1; i<=10; i++){
if(i===5){
break
}
console.log(i)
}
10. Continue statement
for(let i=1; i<=7; i++){
if(i===5){
continue;
}
console.log(i)
}
11.Multiplication table
let num =5;
for (let i = 1; i<=20; i++){
console.log(num + ' x' + i + ' =' + (i*num))
}
12.Factorial of a number
let num = 5
let fact = 1
for (let i =1; i<= num; i++){
fact*=i
}
console.log(fact)
13.Check whether a number is prime
let num = 8
let count = 0
for(let i=1; i<=num; i++){
if(num%i === 0){
count++;
}
}
if(count === 2){
console.log("Prime")
}else{
console.log("Not Prime")
}
14.Check if a number is palindrome
let num = 120
let str = num.toString()
let rev = str.split("").reverse().join("")
if (str === rev) {
console.log(num + " is a palindrome");
} else {
console.log(num + " is not a palindrome");
}