tags:

views:

399

answers:

5

i just want to know that whether i can generate a multiplication table from 1 - 9 with a single for loop??

A: 

I haven't ran this, though the concept is there.

   for(int i = 1; i <= 9; i++){
        Console.WriteLine((i*1).ToString() + " ");
        Console.WriteLine((i*2).ToString() + " ");
        Console.WriteLine((i*3).ToString() + " ");
        Console.WriteLine((i*4).ToString() + " ");
        Console.WriteLine((i*5).ToString() + " ");
        Console.WriteLine((i*6).ToString() + " ");
        Console.WriteLine((i*7).ToString() + " ");
        Console.WriteLine((i*8).ToString() + " ");
        Console.WriteLine((i*9).ToString() + " ");
        Console.Writeline();
    }
Alexander
This code wouldn't build. Console.Write((i * 1).ToString() + " "); would.
KP
Your right Kev, can't cast int to string. Have to call .ToString
Alexander
+5  A: 

Yes, using something like this... But why not using two nested loops?

        for (int i = 0; i < 9 * 9; ++i)
        {
            int a = i / 9 + 1;
            int b = i % 9 + 1;
            Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
        }
sergiom
+1  A: 

To generate the multiplication table of 1-9 with a single for loop you could loop 81 time and use the division and modulo operator to get the two operands.

for (int i = 0; i < 9*9; ++i)
{
  int a = i / 9 + 1;
  int b = i % 9 + 1;
  Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
}

Note, there must be a better way to construct the output, but I'm not familiar with C#.

Mathieu Pagé
See sergioms answer for the proper way to do String formatting in .Net.
Dykam
@Dykam : Thanks.
Mathieu Pagé
A: 

Here's a hint for one way to do it.

How can you extract all of the needed multipliers and multiplicands from a single integer from 0 to 81?

John at CashCommons
not getting it :(((
Abid
Research the modulus operator, `%`.
Dykam
+1  A: 

try:

Console.WriteLine("     1  2  3  4  5  6  7  8  9");

for (int i = 1; i<10; i++)
   Console.WriteLine(
      string.Format("{0}: {1:#0} {2:#0} {3:#0} {4:#0} " +
                    "{5:#0} {6:#0} {7:#0} {8:#0} {9:#0}",
          i, i, 2*i, 3*i, 4*i, 5*i, 6*i, 7*i, 8*i, 9*i)); 
Charles Bretana