PPS Lab · Experiment 6
Multiplication table for a number
CSimple numeric problemsJNTUH R22 · CS108ES
Aim
To write a C program that reads a number and the number of rows, and prints the multiplication table of that number with that many rows, in the form 5 x 1 = 5.
Algorithm
- Read the number n.
- Read the number of rows.
- If the number of rows is less than 1, print a message and stop.
- For i from 1 to the number of rows, print
n x i = n*i.
Program
#include <stdio.h>
int main(void) {
int number, rows;
printf("Enter the number: ");
if (scanf("%d", &number) != 1) {
printf("Invalid input\n");
return 1;
}
printf("Enter the number of rows: ");
if (scanf("%d", &rows) != 1) {
printf("Invalid input\n");
return 1;
}
if (rows < 1) {
printf("Number of rows must be at least 1\n");
return 1;
}
for (int i = 1; i <= rows; i++) {
printf("%d x %d = %d\n", number, i, number * i);
}
return 0;
}Output
Number 5, 3 rows
Enter the number: 5
Enter the number of rows: 3
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15Number 12, 10 rows
Enter the number: 12
Enter the number of rows: 10
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120Recorded by compiling and running this exact program. Typed input appears after each prompt.
How it works
The loop variable i runs from 1 to rows, and each line prints the number, the row number and their product. The number of times the loop body runs is exactly the number of rows.
Common mistakes
Starting the loop at
i = 0, which prints an extra first line5 x 0 = 0. The table starts from 1.Writing
i < rowsinstead ofi <= rows, which prints one row too few.Putting a semicolon after the
forheader, as infor (i = 1; i <= rows; i++);. The loop then has an empty body and theprintfruns only once.Not checking the number of rows. A value of 0 or a negative number prints nothing and gives no message.
Viva questions
Try to answer each one aloud before you open it.
What are the three parts of a for loop?
Initialisation (
i = 1), condition (i <= rows) and update (i++). The initialisation runs once, the condition is checked before each pass, and the update runs after each pass.How many times does the loop body run in this program?
Exactly
rowstimes, for i = 1, 2, ..., rows.How would you write the same table with a while loop?
Set
i = 1before the loop, writewhile (i <= rows), and puti++as the last statement inside the loop body.What happens if a semicolon is placed right after the for header?
The semicolon becomes the empty body of the loop. The loop runs without doing anything, and the statement after it runs only once.