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

355
Visualizações
Javascript Multiplication table in 2D array

I've a task to write a program that creates a multiplication table for the given variable n. The results need to be saved to a two-dimensional array. In the console I need to display the entire table with appropriate data formatting (as below). I'm starting with Javascript and already know loops and arrays only, I haven't learnt functions yet so I need some really basic solution. This is how the result should look like:

enter image description here

Here is my code that I wrote so far and I don't know what to do next:

const n = 3;
const calc = []

for (let i = 1; i <= n; i++) {
    for (let j = 1; j <= n; j++) {
        calc.push(i + " * " + j + " = " + (i * j));
    }
    console.log(calc)
}

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

0

You're almost there:

  • Not sure that you need the array calc if your aim is to print the table
  • Define a new variable row inside the outer loop as an empty array, [];
  • In the inner loop, instead of calc.push, use row.push
  • After the inner loop, you have a complete row, which you can output using the array .join() method
  • If you need to, then add the row to calc with calc.push(row); not necessary in my view.

const n = 3;
//const calc = []; //may not be necessary

for (let i = 1; i <= n; i++) {
    const row = [];
    for (let j = 1; j <= n; j++) {
        row.push(i + " x " + j + " = " + (i * j));
    }
    console.log( row.join(' | ') );
    //calc.push(row);//not sure if you still need this
}
/* OUTPUT
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 2 = 6 | 3 x 3 = 9
*/

about 4 years ago · Juan Pablo Isaza Relatório

0

From the code you've presented, it appears that you're yet to understand what a 2d array really is. The way you've done it, everything's just stuffed into a single 1d array.

You may think of the pixels on a screen as being part of a 2d array. The first array holds all of the horizontal lines. The horizontal lines contain the pixels.

So.. let's concentrate on that part first.

let result = [];

for (var y=0; y<n; y++)
{
    result.push( [] );
    for (var x=0; x<n; x++)
    {
        result[y].push( (x+1) * (y+1) );
    }
}

First we create a result array, and then for every row in our table, we add an array that will hold the columns, then for each column in that row, we add the values.

Next, we just step through that table and turn the values into the original equations. We start by ascertaining the dimensions of the array, before we create a table the same size.

function printTable( tbl )
{
    let nRows = tbl.length;
    let nCols = tbl[0].length;
    
    for (var y=0; y<nRows; y++)
    {
        let rowStr = '';
        
        for (var x=0; x<nCols; x++)
        {
            if (x!=0) rowStr += " | ";
            rowStr += `${y+1} x ${x+1} = ${tbl[y][x]}`;
        }
        console.log(rowStr);
    }
}

Chucking it all together, I present the following code. Yes, I know you're not using functions yet - but you can still see the important concepts. You can change it so that the whole equation for each entry in the table is saved, instead of just the answer.

window.addEventListener('load', init, false);

function init()
{
    let result = makeMultTable(3);
    printTable(result);
}

function makeMultTable(n)
{
    let result = [];
    
    for (var y=0; y<n; y++)
    {
        result.push( [] );
        for (var x=0; x<n; x++)
        {
            result[y].push( (x+1) * (y+1) );
        }
    }
    return result;
}

function printTable( tbl )
{
    let nRows = tbl.length;
    let nCols = tbl[0].length;
    
    for (var y=0; y<nRows; y++)
    {
        let rowStr = '';
        
        for (var x=0; x<nCols; x++)
        {
            if (x!=0) rowStr += " | ";
            rowStr += `${y+1} x ${x+1} = ${tbl[y][x]}`;
        }
        console.log(rowStr);
    }
}

about 4 years ago · Juan Pablo Isaza Relatório

0

Multiplication of table in two dimension array

Function name: multiplyNumber

Syntex multiplyNumber(n)

  • n Number to be passed to function to create table upto that number.

Snippet

function multiplyNumber(n){
        let table  = [];
        let data = [];
        for (var i = 1; i <= n; i++){
                for (var j = 1; j <= n; j++){
                        data.push(`${i} x ${j} = ${i * j}`);
                }
        table.push(data); // pushing data to table.
        data = []; //Resetting data array to store new data each time.
        }
        return table;
}

var result = multiplyNumber(3);
console.log(result);
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