Skip to main content
9 of 9
replaced picture with output and removed spurious `&` char from code
Edward
  • 66.6k
  • 4
  • 118
  • 282

Printing a multiplication table in C

I'm a complete beginner, but I'd like to learn how to program. I really started 2 weeks ago.

So I tried the common exercise, aka the multiplication table, but I tried to add little things I learnt recently in order to challenge myself, like functions, tables and pointers even if it's useless here.

The code works well, but I have some warnings when compiling, and I don't know why, like *pointSize = NULL;

Besides, I'm sure my code could be cleaned up, so I'd like you to tell me how I can improve it.

Here's the result:

How long this table should be ? (0 - 50) 5

       |    1  |    2  |    3  |    4  |    5  |
================================================
    1  I    1  |    2  |    3  |    4  |    5  |
-------+-------+-------+-------+-------+-------+
    2  I    2  |    4  |    6  |    8  |   10  |
-------+-------+-------+-------+-------+-------+
    3  I    3  |    6  |    9  |   12  |   15  |
-------+-------+-------+-------+-------+-------+
    4  I    4  |    8  |   12  |   16  |   20  |
-------+-------+-------+-------+-------+-------+
    5  I    5  |   10  |   15  |   20  |   25  |
-------+-------+-------+-------+-------+-------+
/* Multiplication table */

#include <stdio.h>
short tableSize; // Number of multipliers
short question (short *pointSize); // Ask user how many multipliers
void error(short nbUser); // Cherck error
void multTable(); // The table

void main ()
{
    short i = 1, nbMultipliers;
    question(&nbMultipliers);
    error(nbMultipliers);
    tableSize = nbMultipliers;
    
    /* header */
    printf("       |");
    for (i = 1; i <= tableSize; i++)
    {
        printf("  %3u  |", i);
    }
    printf("\n");

    for (i = 1; i <= (tableSize + 1); i++)
    {
        printf ("========");
    }
    printf("\n");
   /* end header */

    multTable(); // the table
}

/* Ask user how many multipliers */
short question (short *pointSize)
{
    *pointSize = NULL;

    printf("How long this table should be ? (0 - 50) ");
    scanf("%u", pointSize);
    printf("\n");
}

void error (short nbUser)
{
    if (nbUser < 0 || nbUser > 50)
    {
        printf("Error : you must enter a number between 0 and 50");
    }
}

/* end Ask user how many multipliers */

void multTable()
{
    short i = 1, j = 1;
    short line[50] = {0};
 
    for (j = 1; j <= tableSize; j++)
    {
        printf("  %3u  I", j);
        for (i = 1; i <= tableSize; i++)
        {
            line[i] = i*j;
            printf ("  %3u  |", line[i]);
        }
        printf("\n");
        for (i = 1; i <= (tableSize + 1); i++)
        {
            printf ("-------+");
        }
        printf("\n");
    }

}