Reputation: 75
I'm currently learning C# and I was trying to print out a list of numbers to the console line. The list that I want to have is as followed:
01 02 03 04 05
06 07 08 09 10
11 12 13 14 15
etc
The only problem that I'm walking against now is that I cant get a new line after 5 numbers are printed.
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 100; i++)
{
if (i < 10)
{
Console.Write(i.ToString("00 "));
}
else
{
Console.Write(i + " ");
}
}
Console.ReadKey();
}
}
}
And it prints out:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 etc
How can I make it so that after every 5 numbers a new line starts? What kind of loop or statement do I have to use in order to get this to work?
Upvotes: 1
Views: 359
Reputation: 2134
Rewrite your program as following
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 100; i++)
{
if (i < 10)
{
Console.Write(i.ToString("00 "));
}
else
{
Console.Write(i + " ");
}
if (i % 5 == 0)
{
Console.WriteLine();
}
}
Console.ReadKey();
}
}
}
Upvotes: 2
Reputation: 726559
A common approach is to check that the number that you have just printed is divisible by five, and print a newline if it is divisible:
if (i % 5 == 0) {
Console.WriteLine();
}
Upvotes: 3