Järgnevalt koostame kaks programmi erinevate korrutustabeli lahenduste genereerimiseks.
Esimeses näiteprogrammis küsitakse kasutajalt mis arvule me korrutist soovime genereerida ning korrutustabel luuakse alates väärtusest 0 kuni väärtuseni 10, mis on defineeritud makrona MULT_LIMIT . Märka, et tsükli tingimuses on võrdluseks <= ehk otspunkt on kaasa arvatud – enamasti me otspunkte ei kaasa, küll aga antud juhul on meil see vajalik
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; } |
Järgmises näites vaatame üksteise sisse paigutatud tsükleid (nested loops) ja leiame kogu korrutustabeli vahemikus 1 – 10.
Märka, et erinevalt tavapärasest algavad tsükliloendurid väärtusest 1 ja lõpp-punkt on jällegi kaasa arvatud. Jälgi ka reavahetuse paigutust ning tühikutega vastuste polsterdamist! Mõtle läbi mida ja miks tehakse printf lausetega!
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; } |