Placement Prep

Multiplication Table Program in C, C++, Java, and Python

Write a multiplication table program in C, C++, Java, and Python using for and while loops. Includes algorithm, sample I/O, output formatting, and placement context.

By FACE Prep Team 6 min read
multiplication-table programming c-programming python java placement-prep for-loop while-loop

The multiplication table program tests loop fluency without ambiguity, which is why TCS NQT, Infosys SP, Wipro NLTH, and Cognizant GenC all use it as a coding warm-up.

Why This Appears in Placement Coding Rounds

Most placement coding assessments split into two tiers: a warm-up block where every candidate is expected to score full marks, and a harder block where fewer do. The multiplication table lives in the warm-up tier because its algorithm has no hidden complexity. The loop bounds are explicit, the output format is fixed, and an automated judge can verify the result in milliseconds.

The TCS iON NQT, most recently conducted in October 2025, typically opens its coding section with exactly this kind of problem: print a series, generate a table, compute a sum. The scoring is binary. Your output either matches the expected output character-for-character, or it does not. That means the challenge is not the algorithm but the precision of the output: the right separator characters, the right spacing, no trailing whitespace, the correct newline at the end of each row.

Infosys SP, Wipro NLTH, and Cognizant GenC Next rounds follow the same two-tier structure. Getting warm-up problems right in under five minutes is what leaves time for the harder problems that differentiate shortlisted candidates from those who are not. The multiplication table, in particular, checks that you can control a loop’s bounds and produce a precisely formatted output; both skills carry directly into harder problems in the same session.

Algorithm and Input-Output Format

The algorithm is four steps:

  • Read the base number (num) from standard input.
  • Read the end value (end), which determines how many rows the table prints.
  • Loop from i = 1 to i = end (inclusive).
  • For each iteration, print the line: num * i = result.

The input and output format used in most placement judges:

Input:

1
5

Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5

Notice that both the * and = are surrounded by single spaces. A format string that outputs 1*1=1 instead of 1 * 1 = 1 fails the judge even if the arithmetic is correct. The sample I/O in the problem statement is the contract; match it exactly.

C Program to Display the Multiplication Table

For-Loop Variant

#include <stdio.h>
int main() {
    int num, end;
    scanf("%d", &num);
    scanf("%d", &end);
    for (int i = 1; i <= end; i++) {
        printf("%d * %d = %d\n", num, i, num * i);
    }
    return 0;
}

Sample run with input 5 and 10:

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

The printf format string "%d * %d = %d\n" does the formatting work: three %d placeholders for num, i, and num * i, with literal spaces and a newline already embedded. Two separate scanf calls match the two-lines input format.

While-Loop Variant

#include <stdio.h>
int main() {
    int num, end, i;
    scanf("%d", &num);
    scanf("%d", &end);
    i = 1;
    while (i <= end) {
        printf("%d * %d = %d\n", num, i, num * i);
        i++;
    }
    return 0;
}

The while-loop spreads loop control across three statements: initialization before the loop, the condition in the while header, and the increment (i++) inside the body. The output is identical. The for-loop version is preferred in timed tests because all three control elements appear in a single header line, reducing the chance of forgetting the increment.

C++ Program

#include <iostream>
using namespace std;
int main() {
    int num, end;
    cin >> num >> end;
    for (int i = 1; i <= end; i++) {
        cout << num << " * " << i << " = " << num * i << endl;
    }
    return 0;
}

C++ replaces scanf/printf with cin/cout. The cin >> num >> end syntax reads both integers in one statement since cin treats both spaces and newlines as delimiters. The cout chain is more verbose than a printf format string for multi-part output, but it avoids format-string typos. Either approach is accepted by standard online judges.

Java Program

import java.util.Scanner;
public class MultiplicationTable {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int end = sc.nextInt();
        for (int i = 1; i <= end; i++) {
            System.out.printf("%d * %d = %d%n", num, i, num * i);
        }
        sc.close();
    }
}

Java requires a class declaration and a Scanner import. That is the visible boilerplate compared to C or Python. System.out.printf uses the same format-string syntax as C’s printf, with one change: %n is the platform-independent newline. Both %n and \n work on most online judges, but %n is the idiomatic Java choice and avoids rare platform issues.

Python Program

For-Loop Variant

num = int(input())
end = int(input())
for i in range(1, end + 1):
    print(f"{num} * {i} = {num * i}")

Python reduces the whole program to four lines. The f-string syntax evaluates expressions inside {} at runtime, making the format string easier to read than %d-style placeholders. Note that range(1, end + 1) is necessary because Python’s range excludes its upper bound, so writing range(1, end) would stop one row short.

While-Loop Variant

num = int(input())
end = int(input())
i = 1
while i <= end:
    print(f"{num} * {i} = {num * i}")
    i += 1

Functionally identical to the for-loop version. Use the for-loop in placement tests unless the problem specifically asks for a while-loop, since range-based iteration is the idiomatic Python approach and faster to write correctly under a timer.

For-Loop vs While-Loop: Which to Use in a Timed Test

The for-loop is the default for counter-based problems. It puts initialization, condition check, and increment in a single header line, making the loop’s behavior immediately readable to anyone reviewing the code.

The while-loop is the right choice when the exit condition is not a simple counter. Reading until a sentinel value (such as -1), processing input until EOF, or running until a flag changes: those are while-loop scenarios. For the multiplication table, the counter is explicit and the upper bound is known before the loop starts, so the for-loop is cleaner.

One practical risk in timed tests: forgetting i++ inside a C or Java while-loop body produces an infinite loop that hangs the judge and costs the full time penalty. The for-loop makes that mistake structurally harder. For a related loop-based problem where the same reasoning applies, see the sum of digits program.

Cross-Language Comparison

FeatureCC++JavaPython
Input methodscanfcinScanner.nextInt()int(input())
Loop headerfor (int i=1; i<=end; i++)for (int i=1; i<=end; i++)for (int i=1; i<=end; i++)for i in range(1, end+1):
Output callprintfcout <<System.out.printfprint(f"...")
Format style%d * %d = %dstream chain%d * %d = %df-string
Visible boilerplatelowlowhighnone

The algorithm is identical in all four. Python is fastest to write. C is expected in competitive programming rounds that restrict standard libraries. Java is familiar to most CSE students from lab coursework. Choose based on what you can write correctly under a timer, not on what you think looks most impressive.

For a broader look at how algorithm structure affects memory usage across languages, the space complexity guide covers the theory that matters when placement rounds move from warm-up problems to harder ones.

Common Mistakes and How to Avoid Them

The multiplication table has a small surface area for bugs, but the same errors appear repeatedly across candidates:

  • Off-by-one in the loop bound. Using i < end instead of i <= end prints one fewer row than the judge expects. In Python, writing range(1, end) instead of range(1, end + 1) produces the same off-by-one error.

  • Wrong spacing in the output format. If the expected output is 5 * 3 = 15 and your code prints 5*3=15, the judge marks it wrong. The spaces around * and = are part of the output contract.

  • Missing the newline at end of each row. In C and C++, printf and cout need an explicit \n or endl. Omitting it prints all rows on one line.

  • Reading both inputs on the same line. If the judge sends inputs on two separate lines and your code reads them as a space-separated pair on one line, some languages handle it correctly and some do not. The safe pattern is one read call per variable, as all four programs above demonstrate.

For a related problem where input-parsing mistakes are the primary source of wrong answers, see the replace 0s with 1s program.


Python’s one-line f-string approach scales directly to scripts that call real APIs: the for i in range(1, end + 1): loop becomes for prompt in prompts:, with a live model call inside the loop body. TinkerLLM at ₹499 puts real LLM API calls in your hands so you can write that exact pattern in Python against a production model. The resulting project belongs on your GitHub profile in a way that a multiplication table, by design, does not.

Primary sources

Frequently asked questions

What is the time complexity of a multiplication table program?

O(n), where n is the end value. The loop runs exactly n iterations, each doing one multiplication and one print operation. Space complexity is O(1) since no array is used.

Can I use recursion instead of a loop to print a multiplication table?

Yes. A recursive function prints num * i, then calls itself with i+1 until i exceeds the end value. Iterative is preferred in placement tests for readability and to avoid stack-overflow questions.

How is multiplication table input formatted in TCS NQT problems?

Typically two integers on separate lines: the base number first, then the end value. Always check the problem statement's sample input before submitting, since some variants use space-separated input on one line.

Which language is best for the multiplication table in a placement coding test?

Python is fastest to write and debug under time pressure. C and C++ are expected in competitive programming rounds. Java adds class boilerplate but is familiar to most CSE students. Use the language you can write correctly without looking up syntax.

How do I stop the table at a custom end value instead of always printing 1 to 10?

Read the end value as a second input and use it as the loop upper bound. In Python, use range(1, end + 1). In C, use i <= end in the for condition. The programs on this page all follow this pattern.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹499)
Free AI Roadmap PDF