Solution 1 :

Problem Description

  • We need a way to create a table of numbers starting at 0 till the last number provided to us by the user.
  • The last number must be between 1 and 500. (You can adjust the range as per your need.)

Solution Implemented in above code:

  • Columns – 10, Number = 30, Rows = (num / columns = 3)

Problems faced in above code:

  • Columns – 10, Number = 32, Rows = (num / columns = 3)

The no of rows is still 3, but we need atleast 4 rows to accomodate 32 numbers in 10 columns.

  • Data in each column printed is 32 if you enter 32 via prompt.

Visual Representation?

To understand the problem in our proposed solution, let us write what’s happening under the hood.

Num / columns = No_of_Rows
30 / 10 = 3.0
31 / 10 = 3.1
32 / 10 = 3.2
33 / 10 = 3.3
34 / 10 = 3.4
35 / 10 = 3.5
36 / 10 = 3.6
37 / 10 = 3.7
38 / 10 = 3.8
39 / 10 = 3.9
40 / 10 = 4.0

300 / 10 = 30.0
301 / 10 = 30.1
...

This calculation provides us a hint that if our formula to compute no of rows is incorrect. The error occurs due to remainder in our code.

If we could somehow use this remainder to caluclate no of rows, then issue should be fixed.

What if we could increment no of rows by 1 if remainder is greater than 0 but less than 10? I think you got the point.

Now, It’s time to modify our code to consider remainder.

// Read it as: if num modulo 10 is greater than 0 and less then 10 then increment row by 1 else don't
let rows = ((num % 10) > 0 && (num % 10) < 10) ? (num / 10) + 1 : num / 10;

So, replacing our no of rows by above code should fix the issue.

Solution 1

Here is complete code with issue fixed:

<html>
  <head>
    <style>
      table {
        width: 70%;
      }
    </style>
    <script>
      let num = window.prompt("What is the loop maximum.? (between 1 and 500)");
      if (num < 0 || num > 500) {
        window.alert(
          "Warning! Must be between 1 and 500. Setting to default 100"
        );
      }
    </script>
  </head>
  <body>
    <h1>Javascript Loops and Functions</h1>
    <br />
    <script>
      document.write("<table border=1>");
      let rows = num % 10 > 0 && num % 10 < 10 ? num / 10 + 1 : num / 10;
      for (row = 1; row <= rows; row++) {
        document.write("<tr>");
        for (col = 1; col <= 10; col++) {
          document.write("<td>" + num + "</td>");
        }
        document.write("</tr>");
      }
      document.write("</table>");
    </script>
  </body>
</html>

Final Solution

  • Fix problem of printing same no in all columns:
  • Fix problem of printing nos in all 10 columns when not required(in case of 32)
<html>
  <head>
    <style>
      table {
        width: 70%;
      }
    </style>
    <script>
      let num = window.prompt("What is the loop maximum.? (between 1 and 500)");
      if (num < 0 || num > 500) {
        window.alert(
          "Warning! Must be between 1 and 500. Setting to default 100"
        );
      }
    </script>
  </head>
  <body>
    <h1>Javascript Loops and Functions</h1>
    <br />
    <script>
      document.write("<table border=1>");
      // Formula to calculate no of rows.
      let rows = num % 10 > 0 && num % 10 < 10 ? num / 10 + 1 : num / 10;
      let count = 0; // Variable to keep track of numbers printed till now.
      for (row = 1; row <= rows; row++) {
        document.write("<tr>");
        for (let i = 1; i <= 10; i++) {
          if (count >= num) break; // Exit early if we already printed nos in less than 10 columns.
          document.write("<td>" + count + "</td>");
          count++;
        }
        document.write("</tr>");
      }
      document.write("</table>");
    </script>
  </body>
</html>

Solution 2 :

In this case you don’t need a number of rows. You only need to trigger adding <td> elements into <tr> if cellNumber % columns === 0 inside your loop.

You forgot about:

  • number that you got from window.prompt … is in fact a string – you have to convert it to an integer with parseInt()
  • set that default value to 100 as you mentioned in the alert ^^

I must also mention that using document.write() is considered to be a bad practise. It’s better to use document.createElement() to create DOM elements and parentElement.appendChild(element) to insert DOM elements into another DOM elements.

With using document.write() you also limit yourself to adding elements into <body>. Handling with DOM elements gives you more possibilities – with them you can put such structures anywhere you want.

Here’s a code snippet of a function which generates such table as a DOM element.

const generateTable = (cells, columns = 10) => {
  const table = document.createElement('table');
  let row = document.createElement('tr');

  for(let i = 1; i <= cells; ++i){
    const cell = document.createElement('td');

    cell.textContent = i - 1;
    row.appendChild(cell);

    if(i % columns === 0 || i === cells){
      table.appendChild(row);
      row = document.createElement('tr');
    }
  }

  return table;
};

You can pin a result of such function for example to body DOM element just like in an example below:

const table = generateTable(123, 12);

document.body.appendChild(table);

Here’s my snippet matching it all together with all mentioned cases implemented:

const generateTable = (cells, columns = 10) => {
  const table = document.createElement('table');
  let row = document.createElement('tr');

  for(let i = 1; i <= cells; ++i){
    const cell = document.createElement('td');

    cell.textContent = i - 1;
    row.appendChild(cell);

    if(i % columns === 0 || i === cells){
      table.appendChild(row);
      row = document.createElement('tr');
    }
  }

  return table;
};

window.addEventListener("DOMContentLoaded", () => {
  const numString = window.prompt("What is the loop maximum.? (between 1 and 500)");
  let num = parseInt(numString);

  if (num < 0 || num > 500) {
    window.alert("Warning! Must be between 1 and 500. Setting to default 100");
    num = 100;
  }

  const table = generateTable(num);

  document.body.appendChild(table);
})
*{
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

table{
  border-collapse: collapse;
}

td{
  text-align: center;
  padding: 7px 14px;
  border: 1px grey solid;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Table loop example</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <script src="script.js"></script>
  </body>
</html>

Docs reference:

Solution 3 :

function generateTable(n, columnCount=10) {
      document.write("<table border=1>");
      document.write("<tr>");
      for (i = 0; i < n; i++) {
        if (i % columnCount === 0) {
          document.write("</tr>");
          document.write("<tr>");
        }
        document.write("<td>" + i + "</td>");
      }
      document.write("</tr>");
      document.write("</table>");
    }

That should work for you ^^

Problem :

I need to create a table with html javascript which has the number of cells that are equal to the user input.

Basically, at the start, the user is prompted to enter a number and then a table is created that has number of cells which are equal to the user input number.
The number of columns should be 10.
The tricky part is to get the number of rows.
For example, if the user enters 30, then the table has 10 columns and 3 rows.
The problem comes, if the number is not a multiple of 10.
For example, if the user enters 32, with the code I created I can still get only 10 columns and 3 rows, which is still 30 cells.

In addition, I need to number the cells as well.

Can anyone help me out of this mess?

A picture of the table I need

<html>
  <head>
     <style>
            table{width: 70%;}
     </style>
     <script>
        let num= window.prompt("What is the loop maximum.? (between 1 and 500)")
        if(num<0 || num>500)
        {
            window.alert("Warning! Must be between 1 and 500. Setting to default 
            100")
        }
     </script>
  </head>
  <body>
    <h1>Javascript Loops and Functions</h1><br>
    <script>
        document.write("<table border=1>")
        for (row=1; row<=num/10; row++) {  
            document.write("<tr>")
            for (col=1; col<=10; col++) {
                document.write("<td>"+ num + "</td>")
            }       
            document.write("</tr>")
        }
        document.write("</table>")
    </script>
 </body>

Comments

Comment posted by koshila_dodan

Thank you Jayant, That was explained perfectly. Now I get the full picture very clearly.

Comment posted by koshila_dodan

Thank you Dawid. Your explanation to the solution was perfect. I can now see, what was missing.

By