Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

113
Visualizações
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

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 ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda