You are here: Home / Topics / Make an array of odd numbers using For Loop in JavaScript

Make an array of odd numbers using For Loop in JavaScript

Filed under: JavaScript on 2023-08-06 22:48:31

In this post we will see how to make an array of odd numbers using for loop and while loop. 

We have initialized a blank array with name arr.

Code:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Array of Odd Numbers</title>
</head>
<body>
   <script>
       //method 1
       var arr = [];
       for(i=1; i<100; i+=2){
           arr.push(i);

       }
       console.log(arr);

 

       //method 2
       /*
       in this method we will make use of remainder (%) operator let' see
       */
      var arr2 = [];
      var num = 1;
      while(num< 100){
       if(num % 2 != 0){
           arr2.push(num);
       }
       num++;
      }

      console.log(arr2);
   </script>
</body>
</html>

 

Output of Code in console will be: 

(50) [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]


(50) [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]

About Author:
S
Shyam Dubey     View Profile
If you are good in any field. Just share your knowledge with others.