Knowee
Questions
Features
Study Tools

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.

🧐 Not the exact question you are looking for?Go ask a question

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:

  1. 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.

  2. The JavaScript part of the code defines a function printOddNumbers that is called when the button is clicked.

  3. Inside the function, we first get the value of the input field using document.getElementById('num').value.

  4. We then initialize an empty string output to store the odd numbers, and a for loop to generate the odd numbers. The loop starts with i = 1 (the first odd number), and increments i by 2 in each iteration to get the next odd number. The loop continues until we have generated num odd numbers (count < num).

  5. In each iteration of the loop, we append the current odd number to output followed by a space.

  6. Finally, we display the odd numbers in the paragraph using document.getElementById('output').innerHTML = output.

This problem has been solved

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

1/1

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.