Hey folks.

I currently have the below code:-

int double weeksInYear = 52;
int double num;

while (num <= weeksInYear)

Console.WriteLine("Week " + num);
num += 2;

Now when my code runs, it produces approximately 26 lines of text as below:-

Week 1
Week 3
Week 5
etc..... (up until Week 51)

What I'd like to do is format the Console.WriteLine aspect of the code so that it prints the results in a column-like / tab-delimited way as below with a space between each entry in each row:-

Week 1 Week 3 Week 5
Week 7 Week 9 Week 11
etc.....

Any suggestions?

Recommended Answers

All 4 Replies

How about this:

int columnsWritten = 0;
for (int week = 1; week <= 52; week++)
{
    if (week % 2 == 0) continue; //Skip even weeks, even number modolu 2, will be zero

    if (columnsWritten > 0)
        Console.Write("\tWeek: " + week.ToString("00")); //ToString(00) format int always as two digits, mainly to make the tabs work
    else
        Console.Write("Week: " + week.ToString("00")); //First column, should not add a tab infront
    columnsWritten++;

    if (columnsWritten == 3) //reset when 3 columns written
    {
        columnsWritten = 0;
        Console.Write("\r\n"); //Move cursor to new line
    }
}

Console.WriteLine("Week{0\tWeek{1}\tWeek{2}", 1, 3, 5);
will print the line: Week1 Week3 Week5

How about this:

int columnsWritten = 0;
for (int week = 1; week <= 52; week++)
{
    if (week % 2 == 0) continue; //Skip even weeks, even number modolu 2, will be zero

    if (columnsWritten > 0)
        Console.Write("\tWeek: " + week.ToString("00")); //ToString(00) format int always as two digits, mainly to make the tabs work
    else
        Console.Write("Week: " + week.ToString("00")); //First column, should not add a tab infront
    columnsWritten++;

    if (columnsWritten == 3) //reset when 3 columns written
    {
        columnsWritten = 0;
        Console.Write("\r\n"); //Move cursor to new line
    }
}

Worked a treat - thanks Lanny

Yeah Lanny great code. :)
An improvement would be to write your for statement as
for (int week = 1; week <= 52; week += 2)
That way you can remove the mod on line 4.
Modulo is an "expensive" operation, so if you can avoid it ...
In this case the difference would play no role, but if you had a for from 1 to 10000000 you would notice the difference.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.