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]);
}
}
-
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] + " "); } }wshcdr– wshcdr2019年09月08日 04:44:45 +00:00Commented Sep 8, 2019 at 4:44
3 Answers 3
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}`);
}
}
answered Sep 7, 2019 at 22:56
Djaouad
22.8k4 gold badges37 silver badges57 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
georg
"just one of them"... or no arrays at all
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]);
}
}
answered Sep 7, 2019 at 23:13
Javier Rey
1,63820 silver badges31 bronze badges
Comments
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
lang-js