Printing even numbers with commas except the last in C# not working

Viewed 350

I have been trying to fix this issue for some days now but can't find the error. It seems as simple as an if statement for the code to print commas for all but the last number. It worked for me putting random numbers but when i put the specific numbers (24,7,35,2,27,7,89)it prints the comma at the end.

Print even numbers with commas

This is my code, but i tried multiple other ways.

using System.Collections.Generic;
using System.Text;
using System.Transactions;

namespace ArrayExercises
{
    class TaskFour
    {
        public static void FindEvenNumbers()
        {
            int[] input = new int[7];
            int count = 1;
            string comma = ",";
            Console.WriteLine("[== Please Enter 7 numbers ==]");
            Console.WriteLine();

            for (int i = 0; i < input.Length; i++)
            {
              Console.WriteLine($"Enter number {count}:");
              input[i] = int.Parse(Console.ReadLine());              
              count++;
            }
            Console.WriteLine("The even numbers in this array are: ");
            for (int i = 0; i < input.Length; i++)
            {
              
                if (input[i] % 2 == 0) 
                {
                    if (i < input.Length)
                    {
                        Console.Write(input[i] + comma);
                    }
                    else
                    {
                        Console.Write(input[i]);
                    }
                }
            }
        }
    }
}

Thanks in advance :)

5 Answers

This answer assumes that the above is homework/tutorial, there are more efficient means that what I am posting here

The problem is this segment:

                if (i < input.Length)
                {
                    Console.Write(input[i] + comma);
                }

The problem is that you are always outputting a comma, regardless of what is to follow. I think that the easiest approach would be to add the comma before hand, meaning, while you are going through the second loop, if you have already printed a number before, you pre-pend a comma and print the number you have, if you did not print any numbers before (that is, you are about to print the first number) then you do not prepend the comma.

You can use below code without introducing any extra space using for loop.

for (int i = 0; i < input.Length; i++)
{
    if (input[i] % 2 == 0)
    {
        if (i != 0) Console.Write(comma);
        Console.Write(input[i]);
        
    }
}

Or use the inbuilt string.Join function.

Console.WriteLine(string.Join(',', input.Where(i => i % 2 == 0)));

Your else condition will never execute. If you are rookie in C# then I would suggest get all even numbers first and store it in the list. Iterate over again to print with comma and just skip the last comma.

//Your existing source code
List<int> evenNumber = new List<int>();
for (int i = 0; i < input.Length; i++)
{
   if (input[i] % 2 == 0) 
   {
       evenNumber.Add(input[i]);
   }
}
for(int i = 0; i < evenNumber.Length; i++)
{
   //Print just number if it is last, otherwise print number with comma
   if(i == evenNumber.Length - 1)
        Console.Write(evenNumber[i]);
   else
        Console.Write(evenNumber[i]+comma);
}

If you know string.Join() then use linq to get list of even numbers and print list of even numbers with ',' as a delimiter

var evenNumbers = input.Where(x => x % 2 ==0);  //Filter all even numbers
Console.WriteLine(string.Join(",", evenNumbers);  //Print using string.Join

i will always be less than the length the input due to the loop's condition.

Instead of implementing this yourself, you could let string.join do the heavy lifting for you:

string result = string.Join(comma, input.Where(i => i % 2 == 0));
Console.WriteLine(result);

Yet another version:

string result = "";
for (int i = 0; i < input.Length; i++)
{
    if (input[i] % 2 == 0) 
    {
        result += $",{input[i]}";
    }
}
Console.WriteLine( result.Length > 0 ? result.Substring(1).ToString() : "");
Related