We will create two example programs to demonstrate use of loops to generate multiplication tables.
Example 1: Multiplication table with used-specified multiplier
In the first program, we will ask the user for the multiplier and generate the multiplication table for that value from 0 to 10, which is defined as a macro MULT_LIMIT . Notice, that the loop condition uses <= – this means that the ending value is inclusive, which is typically not what we would want, but in this case we do.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
/** * File: mult1.c * Author: Risto Heinsar * Created: 18.01.2023 * Edited: 20.06.2025 * * Description: Sample code for looping, demonstrating how to generate a * multiplication table for a single number. */ #include <stdio.h> #define MULT_LIMIT 10 int main(void) { int multiplier; printf("Enter the number you would like to multiply: "); scanf("%d", &multiplier); printf("Generating multiplication table of %d from 0 to %d\n", multiplier, MULT_LIMIT); // Loop for multiplication, end value is inclusive for (int i = 0; i <= MULT_LIMIT; i++) { // Calculate answer int product = multiplier * i; // Print the operation and the answer printf("%d * %d = %d\n", multiplier, i, product); } return 0; } |
Algorithm for the task
In the diagram, notice the control flows – when using loops, the control flow returns to an earlier point. It’s also important to have the condition correctly formed and located. In this case, we are using an entry-controlled loop.
Example 2: Complete multiplication table
In the second example, we will take a look at nested loops and produce a full multiplication table from 1 to 10.
Notice, that contrary to usual, the starting value of the counters is 1 and the ending value is again inclusive. Also notice the location of the line change and padding the answers with spaces! Think how and when the printf() statements are being used!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
/** * File: mult2.c * Author: Risto Heinsar * Created: 18.01.2023 * Edited: 20.06.2023 * * Description: Sample code for nested loops, demonstrating how to generate * a full multiplication table. */ #include <stdio.h> #define MULT_LIMIT 10 int main(void) { // Picking out the value for multiplication for (int i = 1; i <= MULT_LIMIT; i++) { // Picking out the column value for multiplication for (int j = 1; j <= MULT_LIMIT; j++) { // Calculate the product int product = i * j; // Display the product with 3 characters of spacing for alignment // All numbers are printed in the same printf("%3d ", product); } // Reached the end of a line (1 x 10, 2 x 10, etc), print a newline printf("\n"); } return 0; } |