Horje
Print all Even Numbers in a Range in JavaScript Array

We have to find all even numbers within a given range. To solve this question we are given the range(start, end) in which we have to find the answer.

There are several ways to print all the even numbers in a range in an array using JavaScript which are as follows:

Using for Loop in JavaScript

In this method, a “for” loop is used to iterate through a given range of numbers. It identifies even numbers within this range by checking if the current number’s remainder, when divided by 2, is zero. If so, it prints the even number.

Example: To print all the even number within a specific range in JavaScript using for loop.

Javascript

// JavaScript program to print all even
// numbers in a range using for loop
let start = 4;
let end = 15;
 
for (let even = start; even <= end; even += 2) {
  console.log(even);
}

Output

4
6
8
10
12
14

Time Complexity: O(n)

Space Complexity: O(1)

Using While Loop in JavaScript

In this method, we uses a “while” loop to iteratively identify and print even numbers within a specified range. The loop continues until the end of the range is reached.

Example: To find all the even number in a range in JavaScript using while loop.

Javascript

// JavaScript program to print even
// numbers in a given range using while loop
let start = 4;
let end = 15;
 
let current = start;
while (current <= end) {
  if (current % 2 === 0) {
    console.log(current);
  }
  current += 2;
}

Output

4
6
8
10
12
14

Time Complexity: O(n)

Space Complexity: O(1)

Using forEach Loop in JavaScript

In this method, it combines a “for” loop with a “forEach” loop to identify even numbers in a given range. It populates an array with even numbers and then prints each element using “forEach”.

Example: To print all the even numbers in a range in JavaScript using forEach loop.

Javascript

// JavaScript program to print even
// numbers in a given range using forEach loop
let start = 4;
let end = 15;
 
let evenArray = [];
 
for (let num = start; num <= end; num++) {
  if (num % 2 === 0) {
    evenArray.push(num);
  }
}
 
evenArray.forEach((evenNumber) => {
  console.log(evenNumber);
});

Output

4
6
8
10
12
14

Time Complexity: O(n)

Space Complexity: O(n)




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
Print all Odd Numbers in a Range in JavaScript Array Print all Odd Numbers in a Range in JavaScript Array
Print ASCII Value of a Character in JavaScript Print ASCII Value of a Character in JavaScript
How to Create a Typed Array from an Object with Keys in TypeScript? How to Create a Typed Array from an Object with Keys in TypeScript?
How to Remove Multiple Object from Nested Object Array ? How to Remove Multiple Object from Nested Object Array ?
What is the use of the parseFloat() function in JavaScript? What is the use of the parseFloat() function in JavaScript?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15