Home > Enterprise >  Write a program that creates a multiplication table for the given variable n in Javascript
Write a program that creates a multiplication table for the given variable n in Javascript

Time:10-31

Write a program that creates a multiplication table for the given variable n in Javascript

Return the result in a two dimensional array in variable calc. The values in this array should be calculations in the form of text

For example for n = 3 we should get folowing result

1 x 1 = 1 | 1 x 2 = 2 | 1 x 3 = 3
2 x 1 = 2 | 2 x 2 = 4 | 2 x 3 = 6
3 x 1 = 3 | 3 x 3 = 6 | 3 x 3 = 9

My code is :

const number = parseInt(prompt("Enter a number : "));
let calc = new Array(number);
for (let i = 1; i <= number; i  ) {

    for (let x = 1; x <= number; x  ) {
        const result = i * x;
        calc[x] = `${i} * ${x} = ${result}`;
    }

    console.log(calc);
}

But in array the values arent correct. What i am doing wrong ?

CodePudding user response:

You could use Array.map here (twice). Because array indexes are zero based, you should add 1 to them for the result.

const multiplicationTable = number => [...Array(number)]
  .map((n, i) => [...Array(number)]
    .map((v, j) =>
      `${i 1} * ${j 1} = ${(i 1) * (j 1)}`).join(' | '));

document.querySelector(`pre`).textContent = 
  JSON.stringify(multiplicationTable(3), null, 2);

// or create/display as a multiplication table (html)
const asTable = number => {
  const rows = [...Array(number)]
    .map((n, i) => `<tr><td>${i   1}</td>${
        [...Array(number)].map( (v, j) => 
          `<td>${(i   1) * (j   1)}</td>`).join(``) }</tr>`);
  const header = `<thead><tr><th></td>${
    [...Array(number)].map( (v, i) => `<th>${i 1}</th>`).join(``) }</tr></thead>`;

  document.body.insertAdjacentHTML(`beforeend`, `<table>${
  header}${rows.join(``)}</table>`);
}

asTable(8)
body {
  font: normal 12px/15px verdana, arial, sans-serif;
  margin: 2rem;
}

th {
  min-width: 2em;
  text-align: center;
  font-weight: bold;
}

td {
  border: 1px solid #ccc;
  text-align: center;
}

td:nth-child(1) {
  text-align: right;
  border: none;
  font-weight: bold;
}
<pre></pre>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related