Search code examples
c#for-loopseparator

Loop to write a cimma separated list of items


I need to write a for loop that prints 49 through 1, with each value separated by a comma. So, it must not print a comma after the last value.

I have this so far and have no clue , after an hour of research, what else to do.

For (int i = 49; i >= 1; i--)
{
    Console.WriteLine(i + ",");
}

Solution

  • Just check where you are in your loop to know if you need to print the comma.

            public static void Test()
            {
                for (int i = 49; i >= 1; i--)
                {
                    Console.WriteLine(i + (i != 1 ? "," : ""));
                }
    
                Console.ReadLine();
            }