Write an HTML and JavaScript program which accepts N as input and print first Nodd numbers
Question
Write an HTML and JavaScript program which accepts N as input and print first N odd numbers.
Solution
Sure, here is a simple HTML and JavaScript program that accepts N as input and prints the first N odd numbers.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Print N Odd Numbers</title>
</head>
<body>
<h2>Enter a number:</h2>
<input type="number" id="num" placeholder="Enter a number">
<button onclick="printOddNumbers()">Submit</button>
<p id="output"></p>
</body>
</html>
JavaScript:
function printOddNumbers() {
var num = document.getElementById('num').value;
var output = '';
for (var i = 1, count = 0; count < num; i += 2, count++) {
output += i + ' ';
}
document.getElementById('output').innerHTML = output;
}
Here's how it works:
-
The HTML part of the code creates a simple webpage with an input field for the user to enter a number, a button to submit the number, and a paragraph to display the output.
-
The JavaScript part of the code defines a function
printOddNumbers
that is called when the button is clicked. -
Inside the function, we first get the value of the input field using
document.getElementById('num').value
. -
We then initialize an empty string
output
to store the odd numbers, and a for loop to generate the odd numbers. The loop starts withi = 1
(the first odd number), and incrementsi
by 2 in each iteration to get the next odd number. The loop continues until we have generatednum
odd numbers (count < num
). -
In each iteration of the loop, we append the current odd number to
output
followed by a space. -
Finally, we display the odd numbers in the paragraph using
document.getElementById('output').innerHTML = output
.
Similar Questions
Create an HTML and JavaScript program which accepts N as input and print first Nodd numbers
What will be the output of the following code snippet?var a = 1; var b = 0; while (a <= 3) { a++; b += a * 2; print(b); }*4 10 181 2 3None of Above1 4 7
Below is the table of values of a function. Write the output when the input is n.
Construct a Pseudocode to take three numbers and print largest and smallest among them.
Input FormatThe first line of input consist of a Binary numberOutput FormatPrint the decimal equivalent for the given Binary number
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.