What are Odd Numbers? | Maths Explanation for JavaScript Kids
Odd numbers are numbers that are not divisible by 2.
They include:
In this beginner-friendly Maths JavaScript tutorial for kids, we'll explore how to list odd numbers
using JavaScript loops and conditions - perfect for primary school students learning to code.
To generate odd numbers in JavaScript, we use a 'while' loop combined with a conditional statement.
This simple JavaScript exercise will help you understand number patterns and logic.
Create a new file; On Notepad++: File, New.
Call it OddNumbers.html.
Type out the adjoining JavaScript code for listing odd numbers.
Code for Odd Number List with User Input in JavaScript
For a little more flexibility, let's add an input form.
We have used a function here.
A function is a chunk of code that is executed when it is called upon,
such as when an event occurs.
So! JavaScript Fun Practice Exercise - List Odd Numbers
As a fun practice exercise, feel free to try out your own boundary values, and see how the JavaScript code lists the odd numbers between those boundary values.
JavaScript Code for Odd Numbers
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Listing Odd Numbers</title>
</head>
<body>
<h3>Odd Numbers Between 1 and 99</h3>
<div id="odd_numbers"></div>
<script>
var first = 1;
var last = 99;
while (first <= last) {
if ((first % 2) != 0) {
document.getElementById("odd_numbers").innerHTML += first + ", ";
}
first = first + 1;
}
</script>
</body>
</html>
JavaScript Code for Odd Numbers - Collecting range from user.
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Listing Your Own Range of Odd Numbers</title>
</head>
<body>
<h3>Odd Numbers for a Range of your Choice</h3>
<form name="users_range" action="javascript:diplayNumbers()">
Enter Start Number: <input type="number" name="start"><br />
Enter End Number: <input type="number" name="end"><br /><br />
<button onclick="displayNumbers()">Show My List</button>
</form>
<br />
<!-- Users result will be shown here. -->
<div id="odd_numbers">Your range appears here.</div>
<script>
var result_text = ""; // Put the result here for speed advantage.
function displayNumbers() {
/* Obtain an array of the form object that holds the user inputs. */
var form_for_user_input = document.forms["users_range"];
/* From the above array, retrieve the users first and last numbers. */
var first = form_for_user_input["start"].value;
first = parseInt(first); // convert input to number type
var last = form_for_user_input["end"].value;
last = parseInt(last); // convert input to number type
/* Now we can loop through and display the users choice range. */
while (first <= last) {
if ((first % 2) != 0) {
result_text += first + " ";
}
first += 1; // same as "first = first + 1"
}
document.getElementById("odd_numbers").innerHTML = result_text;
}
</script>
</body>
</html>