faca
faca

Reputation: 53

Multiplication table structure

Question about structure of this multiplication table..

How do I make spaces so the output would be like this:

      1 X 9 + 2 = 11
     12 X 9 + 3 = 111
    123 X 9 + 4 = 1111
   1234 X 9 + 5 = 11111
  12345 X 9 + 6 = 111111
 123456 X 9 + 7 = 1111111
1234567 X 9 + 8 = 11111111

Code:

#region MTABLE

int number1 = 1;

for (int i = 2; i <= 8; i++)

{
    int number2 = number1 * 9 + i;
    Console.WriteLine("{0} x {1} + {2} = {3}  ", number1, 9, i, number2);
    number1 = number1 * 10 + i;

    for (int j = 1; j <= i; j++)
    Console.Write(" ");
}

Console.ReadKey();

#endregion

My code currently outputs:

1 x 9 + 2 = 11
  12 x 9 + 3 = 111
   123 x 9 + 4 = 1111
    1234 x 9 + 5 = 11111
     12345 x 9 + 6 = 111111
      123456 x 9 + 7 = 1111111
       1234567 x 9 + 8 = 11111111

Upvotes: 1

Views: 404

Answers (2)

Jorge Y.
Jorge Y.

Reputation: 1133

Move the inner loop to the beginning of the outer loop and count backwards from 8-i:

for (int i = 2; i <= 8; i++)
{
    for (int j = 8-i; j >0; j--)
        Console.Write(" ");

    int number2 = number1 * 9 + i;
    Console.WriteLine("{0} x {1} + {2} = {3}  ", number1, 9, i, number2);
    number1 = number1 * 10 + i;
}

Upvotes: 2

itsme86
itsme86

Reputation: 19496

You're close, you just want to count down instead of up. You can do that by subtracting i from 8 in the condition.

for (int j = 1; j <= 8 - i; j++)
    Console.Write(" ");

Upvotes: 0

Related Questions