We will create two example programs to demonstrate loops that both will produce multiplication tables.
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 36 |
/** * File: mult1.c * Author: Risto Heinsar * Created: 18.01.2023 * Edited: 18.01.2023 * * 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 i; int multiplier, answer; 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 (i = 0; i <= MULT_LIMIT; i++) { // Calculate answer answer = multiplier * i; // Print the operation and the answer printf("%d * %d = %d\n", multiplier, i, answer); } return 0; } |
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 what and when is being done with the printf() statements!
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 36 37 38 39 |
/** * File: mult2.c * Author: Risto Heinsar * Created: 18.01.2023 * Edited: 18.01.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) { int i, j; int answer; // Picking out the value for multiplication for (i = 1; i <= MULT_LIMIT; i++) { // Picking out the column value for multiplication for (j = 1; j <= MULT_LIMIT; j++) { // Calculate the product answer = i * j; // Display the product with 3 characters of spacing for alignment // All numbers are printed in the same printf("%3d ", answer); } // Reached the end of a line (1 x 10, 2 x 10, etc), print a newline printf("\n"); } return 0; } |