-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem-7_Find_Even_Numbers_in_an_Array.js
More file actions
43 lines (35 loc) · 1.66 KB
/
Problem-7_Find_Even_Numbers_in_an_Array.js
File metadata and controls
43 lines (35 loc) · 1.66 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
// Problem-7_Find_Even_Numbers_in_an_Array with Solution, Explanation, Verification, and Execution:
// To find even numbers in an array, we can implement the Solution like below:
// -------------------------------------------------------------------
function findEvens(arr) {
let evens = [];
let i = 0;
do {
if (i < arr.length && arr[i] % 2 === 0) {
evens.push(arr[i]);
}
i++;
} while (i <= arr.length);
return evens;
}
// Explanation:
// ---------------
// The function prepares an empty array for even numbers and uses a do-while loop for iteration, ensuring at least one execution. Inside the loop, it checks if the current index is within bounds and if the number is even (remainder of division by 2 is zero); if both are true, it adds the number to the evens array. The index increments each time, and the loop runs until the index exceeds the array length. This structure collects evens in a controlled, loop-driven manner.
// Verification:
// ----------------
// function findEvens(arr) {
// let evens = [];
// let i = 0;
// do {
// if (i < arr.length && arr[i] % 2 === 0) {
// evens.push(arr[i]);
// }
// i++;
// } while (i <= arr.length);
// return evens;
// }
// console.log(findEvens([1, 2, 3, 4, 5, 6]));
// Execution of the above code block in IDE environment with node.js installed:
// ----------------------------------------------------------------------
// Input (In the directory in IDE environment with node.js installed): 'node Problem-7_Find_Even_Numbers_in_an_Array.js'
// Output (In the directory in IDE environment with node.js installed): [2, 4, 6]