QUESTION 36 · Loop Applications
Write a C program to print a multiplication table for a given number of rows.
5 marksAnswer in brief
A multiplication table prints the product of a selected number and each row number from 1 through the requested row count.
Algorithm
- Read number and rows. Check the supported limits.
- Start i at 1.
- While i <= rows, print number, i and number * i; then increment i.
- 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