Ralvarez
Ralvarez

Reputation: 31

How do I print the output in one row below another?

For example I am trying to print the output in following way:
disk: 1 2 3 4 5
move: 1 3 7 15 31
How can I do that, can someone help me out please?

{
    class Program
 {
    static void Main(string[] args)
    {
        int n = 2;

        for (int j = 1; j <= 5; j++)
            Console.WriteLine("disk: {0}", j);

        for (int i = 1; i <= 5; i++)                               
                Console.WriteLine("moves: {2:N0}",
                                  n, i,(long)Math.Pow(n, i) - 1);

    }

  }
}

Upvotes: 2

Views: 641

Answers (3)

crthompson
crthompson

Reputation: 15865

You can use Console.Write and it wont print a carriage return.

However you dont need a for loop in this case. Just use Enumerable.Range

  var n = 2;
  var disks = Enumerable.Range(1, 5).ToList();
  var moves = Enumerable.Range(1, 5).Select(i => (long) Math.Pow(n, i) - 1);
  Console.WriteLine("disk: {0}", string.Join(" ", disks));
  Console.WriteLine("moves: {0:N0}", string.Join(" ", moves));

Results:

disk: 1 2 3 4 5 moves: 1 3 7 15 31

Upvotes: 0

slugster
slugster

Reputation: 49974

Use the string.PadLeft() method to justify your text. Of course you can replace the magic numbers with a constant value. This gives you the advantage of not having to count spaces, and automatically adds the right amount of spaces to bring the string up to the desired length.

Note that you can also get rid of the format insertion (i.e. no more curly braces).

static void Main(string[] args)
{
    int power = 2;

    Console.Write("disk:".PadLeft(8));
    for (int j = 1; j <= 5; j++)
        Console.Write(j.ToString().PadLeft(5));

    Console.WriteLine();
    Console.Write("moves:".PadLeft(8));
    for (int i = 1; i <= 5; i++)
        Console.Write(((long)Math.Pow(power, i) - 1).ToString().PadLeft(5));


    Console.WriteLine();
    Console.ReadLine();
}

This is the result:

enter image description here

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564333

Console.WriteLine will, as it sounds, write a new line each time. If you don't want that behavior, use Console.Write.

Console.Write("Disk:");
for (int j = 1; j <= 5; j++)
     Console.Write(" {0}", j);
Console.WriteLine();

Console.Write("Moves:");
for (int i = 1; i <= 5; i++)                               
     Console.Write(" {2:N0}", (long)Math.Pow(n, i) - 1);
Console.WriteLine();

Upvotes: 2

Related Questions