*****Exercise 4.1 Generate a multiplication table

Recommendation:

Exercise 4-1. Write a program that will generate a multiplication table of a size entered
by the user. a table of size 4, for instance, would have four rows and four columns. the
rows and columns would be labeled from 1 to 4. each cell in the table will contain the
product of the corresponding row and column numbers, so the value in the position
corresponding to the third row and the fourth column would contain 12.

 1 //Exercise 4.1 Generate a multiplication table */
 2 #include <stdio.h>
 3 
 4 int main(void)
 5 {
 6   int table_size = 0;
 7   int col = 0;                      // Table size        */
 8   int row = 0;
 9 
10   printf("Enter the table size (from 2 to 12): ");
11   scanf("%d", &table_size);
12   //////////////////////////////////
13   if(table_size > 12)
14   {
15     printf("Table size must not exceed 12 - setting to 12\n");
16     table_size = 12;
17   }
18   else if(table_size < 2)
19   {
20     printf("Table size must be at least 2 - setting to 2\n");
21     table_size = 2;
22   }
23 /////////////////////////////////////////////////////////////////
24   for(row = 0 ; row <= table_size ; ++row)
25   {
26     printf("\n");                      // Start new row
27     for(col = 0 ; col<=table_size ; ++col)
28     {
29       if(row == 0)                     // 1st row?
30       {                                // Yes - output column headings
31         if(col == 0)                   // 1st column?
32           printf("    ");              // Yes - no heading
33         else
34           printf("|%4d", col);         //No - output heading
35       }
36       else
37       {                                // Not 1st row - output rows
38         if(col == 0)                   // 1st column?
39           printf("%4d", row);          // Yes - output row label
40         else
41           printf("|%4d", row*col);     // No - output table entry
42       }
43     }
44     if(row == 0 )                      // If we just completed 1st row
45     {                                  // output separator dashes
46       printf("\n");
47       for(col = 0 ; col <= table_size ; ++col)
48         printf("_____");
49     }
50   }
51   printf("\n");
52     return 0;
53 
54 }

 

posted @ 2014-12-18 18:49  稳稳稳稳稳稳  阅读(488)  评论(0编辑  收藏  举报