1

Part of my homework I have to write a program that calculates all multiplication tables up to 10 and store the results in an array. The first entry formatting example is "1 x 1 = 1". I think I have my code written right for the nested for loop but I'm not sure on how to output it properly.

var numOne = [1,2,3,4,5,6,7,8,9,10];
var numTwo = [1,2,3,4,5,6,7,8,9,10];
var multiple = [];
for (var i = 0; i < numOne.length; i++) {
  for (var j = 0; j < numTwo.length; j++) {
    multiple.push(numOne[i] * numTwo[j]);
    console.log(numOne[i] * numTwo[j]);
  }
}
1
  • var numOne = [1,2,3,4,5,6,7,8,9,10]; var numTwo = [1,2,3,4,5,6,7,8,9,10]; var multiple = []; for (var i = 0; i < numOne.length; i++) { document.writeln("<br />"); for (var j = 0; j < numTwo.length; j++) { multiple.push(numOne[i] * numTwo[j]); //console.log(numOne[i] * numTwo[j]); document.write(numOne[i] * numTwo[j] + " "); } } Commented Sep 8, 2019 at 4:44

3 Answers 3

1

You can use a template string, and you can just loop through the numbers in the arrays without using arrays (in the same way you were looping through the indices):

var multiple = [];
var m;

for (var i = 1; i <= 10; i++) {
  for (var j = 1; j <= 10; j++) {
    m = i * j;
    multiple.push(m);
    console.log(`${i} * ${j} = ${m}`);
  }
}

Sign up to request clarification or add additional context in comments.

1 Comment

"just one of them"... or no arrays at all
1
var multiple = [];
var first = 1;
var last = 10;

for (var i = first; i <= last; i++) {
  for (var j = first; j <= last; j++) {
    multiple.push(i + " x " + j + " = " + (i*j));
    console.log(multiple[multiple.length-1]);
  }
}

Comments

1

Not sure if ES6 is part of your curriculum, so here is how to do it with and without template literals

// Create the arrays that you want to multiply

var numOne = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var numTwo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Create a function that accepts both arrays as arguments
function multiply(arr1, arr2) {
  var products = [];
  for (var i = 0; i < arr1.length; i++) {
    for (var j = 0; j < arr2.length; j++) {
        //Here we are using template literals to format the response, so that the program will show you the inputs and calculate the answer
      products.push(`${arr1[i]} X ${arr1[j]} = ${arr1[i] * arr2[j]}`); 
      /* If ES6 is outside of the curriculum, the older method for formatting would be like this:
        products.push(arr1[i] + " X " + arr2[j] + " = " + arr1[i]*arr2[j])
      */
    }
  }
  console.log(products);
  return products;
}

// Call the second function example
multiply(numOne, numTwo);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.