Skip to study material
← Question index

QUESTION 36 · Loop Applications

Write a C program to print a multiplication table for a given number of rows.

5 marks

Answer in brief

A multiplication table prints the product of a selected number and each row number from 1 through the requested row count.

Algorithm

  1. Read number and rows. Check the supported limits.
  2. Start i at 1.
  3. While i <= rows, print number, i and number * i; then increment i.
  4. Stop after the requested number of rows.

Worked example

For number = 5 and rows = 3, the multipliers are 1, 2 and 3. The products are 5, 10 and 15. Each iteration prints one line. The loop stops when i becomes 4 because 4 <= 3 is false.

Formatting the output

The printf format displays the table as number x multiplier = product. A newline ends each row. Use a format specifier that matches the product type. In the sample, 1LL * number * i performs the multiplication as long long, and %lld displays the result.

Input cases

A negative number is allowed and produces negative products for positive row numbers. Zero produces zero products. A row count of zero prints no rows. A negative row count is rejected. The sample limits the magnitude of number to 10000 and rows to 1000 to keep arithmetic and output manageable.

Time and space complexity

For r rows, there are r multiplications and r printed lines. Each row involves fixed work, so time is O(r). The selected number changes the products, not the iteration count. Only number, rows and i are required, so auxiliary space is O(1).

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    int number, rows;
    if (scanf("%d%d", &number, &rows) != 2 ||
        number < -10000 || number > 10000 || rows < 0 || rows > 1000) {
        puts("Unsupported input"); return 1;
    }
    for (int i = 1; i <= rows; ++i) {
        printf("%d x %d = %lld\n", number, i, 1LL * number * i);
    }
    return 0;
}

Sample input and output

Input

5 3

Output

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15

Related exam questions

Related questions in the loops category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q6(b) · 8 marks

    How is an entry-controlled loop different from an exit-controlled loop? Explain.

    Paper P01 · page 1
  • March/April 2023 · Q2(b) · 5 marks

    Devise an algorithm for the sum of n numbers using while and for loops.

    Paper P02 · page 1

View this category in the exam question bank →