• IMPORTANT: Welcome to the re-opening of GameRebels! We are excited to be back and hope everyone has had a great time away. Everyone is welcome!

[C] Multiplication Table Display Example

bitm0de

Active Member
Joined
May 24, 2015
Messages
13
Reaction score
0
Code:
#include <stdio.h>

void display_multiplication_table(int height, int width, int pad)
{
  int i, j;
  for (i = 1; i <= height; ++i)
  {
    for (j = 1; j <= width; ++j)
    {
      printf("%*d", pad, i * j);
    }
    fputc('\n', stdout);
  }
}

int main(void)
{
  display_multiplication_table(12, 10, 4);
  return 0;
}

Simple multiplication table display I created when I was bored.

edit: This may even be better for avoiding multiplication:
Code:
void display_multiplication_table(int height, int width, int pad)
{
  int i, j, v;
  for (i = 1; i <= height; ++i)
  {
    v = i;
    for (j = 0; j < width; ++j)
    {
      printf("%*d", pad, v);
      v += i;
    }
    fputc('\n', stdout);
  }
}
 

Zahreah

Well-Known Member
Joined
Mar 31, 2012
Messages
2,822
Reaction score
8
Looks nice. What does the second set of Code do differently exactly?
 

bitm0de

Active Member
Joined
May 24, 2015
Messages
13
Reaction score
0
Instead of multiplying the values of the table, it just creates the multiples for each row by adding the value of the current multiple on the far lefthand side to each previous value. Addition is less expensive than multiplication, so with the added variable, it should be better and more efficient than multiplication still.

Ex:
Code:
1   2   3   4   5  
2   4   6   8  10
3   6   9  12  15
4   8  12  16  20
5  10  15  20  25

Row 1: 1 = 1, (1 + 1) = 2, (2 + 1) = 3 - each following value is the previous value + 1
Row 2: 2 = 2, (2 + 2) = 4, (4 + 2) = 6 - each following value is the previous value + 2

If we know the previous value is 1 multiple less than the following value, why is multiplication needed? In multiplication, you start with a base, and multiply through all of the values each time until we get the next multiple. If we already know the next value is the next multiple of the base number, then it's obvious that addition could be utilized to create a more efficient strategy.
 
Top