Kyle Myott Kyle Myott - 21 days ago 8
C# Question

C# Formatting Long List of Numbers To Be More Compact

Console.WriteLine(" Even Table \n");
int MaxNumber = 100;
int EvenNumbers = 0;
int i;

for (i = 0; i <=MaxNumber; i+=2)
{
if (i % 2 == 0)
{
EvenNumbers = i;
}
Console.Write(EvenNumbers);
}


OUTPUT:

Even Table

0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100


I am making a program that displays the even numbers between 2 and 100 inclusively. I am able to display the even numbers, although the formatting for the output is in a straight line due to the Console.Write, is there a string format that can I use to have the output display each even number, but cut to a new line every interval of 20? So it would look like:

1-20

20-40

40-60

ETC

Answer

Use this:

for (i = 0; i <=MaxNumber; i+=2)
{
    EvenNumbers = i;
    Console.Write(EvenNumbers+" ");
    if(i%20==0){
        Console.WriteLine();
    }
}

You do not need condition if (i % 2 == 0) because your step is 2.