Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[C] Multiplication Table Display Example
#1
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);
  }
}
#2
Looks nice. What does the second set of Code do differently exactly?
#3
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.


Forum Jump:


Users browsing this thread: 1 Guest(s)


Powered by © 2002-2020 MyBB Group.
Theme by CreWix. Fixed by Tomik. Customized for Aeowulf.