Search code examples
javascriptarraysfor-loopmultiplication

Printing multiplication table with 2D array


I'm a really beginner and for now im preparing for JavaScript bootcamp. Unfortunately i stuck with one of pre-work excercises.

My task is to do muliplication table, put it into empty 2D Array and print it precisely in this form:

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

On start I have 2 var declared: const n = 3; const calc = [];

I know i have to start with 'for' loop - and i have no idea whats next;

for (let i = 1; i <= n; i++) { }

EDIT: Thanks for help, correct code below:

const n = 3;
const calc = [];


for(let i = 0; i < n; i++){
    calc[i] = [];
    for(let k = 0; k < n; k++){
        calc[i][k] = (i + 1) + ' * ' + (k + 1) + ' = ' + (i + 1) * (k + 1);
    }
}
for(let i = 0; i < calc.length; i++){
    console.log(String(calc[i]).replaceAll(',', ' | '));
}

Solution

  • You need two 'for' loops to fill the array in 2D. After that you need another 'for' loop to print each row (for example in a paragraph tag).

    Working example:

    const n = 3; 
    const calc = [];
    
    for(i = 0; i < n; i++){
        calc[i] = [];         //add the inner arrays (the second dimension)
        for(k = 0; k < n; k++){ 
            calc[i][k] = (k + 1) + ' x ' + (i + 1) + ' = ' + (k + 1) * (i + 1);
        }
    }
    
    for(i = 0; i < calc.length; i++){ 
        const p = document.createElement("p");
                              //convert each inner array to a string
        p.innerHTML = String(calc[i]).replaceAll(',', ' | ');
        document.querySelector('#container').appendChild(p);
    }
    <div id="container"></div>