Print the Multiplication Table of a Number
Solve this ProblemEasy5–10 min
Topics
BasicsLoops
Companies
TCSInfosysWipro
Given an integer
n, return its multiplication table — n × 1 through n × 10 — as an array of 10 values.
The for loopFor LoopWalking i from 1 to 10, computing n × i each time and collecting the result. version is the school-taught multiplication table, produced mechanically. The range-and-mapRange, MappedGenerating the fixed range 1 through 10 first, then transforming every value with a "multiply by n" function — separating "what values" from "what to do with them." version separates generating the positions (1 through 10) from the transformation applied to them (× n), a pattern that generalizes well beyond just multiplication tables.
Test Case 1:
Input:n = 5
Output:[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Explanation:n times 1 through 10.
Test Case 2:
Input:n = 1
Output:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Explanation:The table of 1 is just 1 through 10.
Test Case 3:
Input:n = 0
Output:[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Explanation:Anything times 0 is 0.
Constraints
- ◆
-100 ≤ n ≤ 100
Try the Dry Run
Approach & Solutions
For Loop — Multiply by Each iGood
Walk i from 1 to 10, computing n × i each time and collecting the result — the standard multiplication table taught in school, just produced by a loop instead of by hand.
Time
O(1) — always exactly 10 multiplicationsSpace
O(1)Java
1class Solution {
2 public int[] multiplicationTable(int n) {
3 int[] result = new int[10];
4 for (int i = 1; i <= 10; i++) {
5 result[i - 1] = n * i;
6 }
7 return result;
8 }
9}Built-in Range, MappedOptimal
Generate the range 1 through 10, then map each value through "multiply by n" — the same ten multiplications, expressed as a transformation of a range instead of a hand-written accumulation loop. C has no map or range built-in, so it keeps the explicit loop.
Time
O(1)Space
O(1)Java
1class Solution {
2 public int[] multiplicationTable(int n) {
3 return java.util.stream.IntStream.rangeClosed(1, 10)
4 .map(i -> n * i)
5 .toArray();
6 }
7}