Multiplication Table
Program to print multiplication table
JavaScript Multiplication Table Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Method 1: Using for loop
let number = 5;
console.log("Multiplication table of", number + ":");
for (let i = 1; i <= 10; i++) {
console.log(number + " × " + i + " = " + (number * i));
}
// Method 2: Using template literals
let num = 7;
console.log("\nMultiplication table of " + num + ":");
for (let i = 1; i <= 10; i++) {
console.log(`${num} × ${i} = ${num * i}`);
}
// Method 3: Using while loop
let n = 9;
let counter = 1;
console.log("\nMultiplication table of " + n + ":");
while (counter <= 10) {
console.log(n + " × " + counter + " = " + (n * counter));
counter++;
}
// Method 4: Function to generate table
function multiplicationTable(number, limit = 10) {
console.log(`Multiplication table of ${number}:`);
for (let i = 1; i <= limit; i++) {
console.log(`${number} × ${i} = ${number * i}`);
}
}
multiplicationTable(6);Multiplication table of 5: 5 × 1 = 5 5 × 2 = 10 5 × 3 = 15 5 × 4 = 20 5 × 5 = 25 5 × 6 = 30 5 × 7 = 35 5 × 8 = 40 5 × 9 = 45 5 × 10 = 50 Multiplication table of 7: 7 × 1 = 7 7 × 2 = 14 7 × 3 = 21 7 × 4 = 28 7 × 5 = 35 7 × 6 = 42 7 × 7 = 49 7 × 8 = 56 7 × 9 = 63 7 × 10 = 70 Multiplication table of 9: 9 × 1 = 9 9 × 2 = 18 9 × 3 = 27 9 × 4 = 36 9 × 5 = 45 9 × 6 = 54 9 × 7 = 63 9 × 8 = 72 9 × 9 = 81 9 × 10 = 90 Multiplication table of 6: 6 × 1 = 6 6 × 2 = 12 6 × 3 = 18 6 × 4 = 24 6 × 5 = 30 6 × 6 = 36 6 × 7 = 42 6 × 8 = 48 6 × 9 = 54 6 × 10 = 60
Understanding Multiplication Table
This program demonstrates different loop types to generate multiplication tables.
For Loop
Most common loop structure:
for (initialization; condition; increment) {
}
// code to executeParts of For Loop:
1.
Initialization
: let i = 1 - runs once at start
2.
Condition
: i <= 10 - checked before each iteration
3.
Increment
: i++ - runs after each iteration
While Loop
Executes while condition is true:
while (condition) {
}
// code
// update conditionImportant:
Must update counter inside loop to avoid infinite loop!
Template Literals
ES6 feature for string interpolation:
`${num} × ${i} = ${num * i}`
Benefits:
Function with Default Parameter
function multiplicationTable(number, limit = 10) {
}
// limit defaults to 10 if not providedLoop Control:
break: Exit loop immediatelycontinue: Skip to next iterationWhen to Use:
-
For loop
: Known iterations, counting
-
While loop
: Unknown iterations, condition-based
-
Function
: Reusable code
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.