I've written a console application (.NET 5.0) in C# in Visual Studio which prints out all the even and odd numbers you give as input.
It works as intended but there is a problem that I will encounter in the future when making similar applications.
Whenever a number isn't odd the respective place of that array (Number_odd) will have a zero added to it. How do I stop that from happening? I currently filtered out all the zero's by not printing any zero.
The output currently looks like "odd: 5 9 7 1 3" with all the zero's filtered. Without filtering the output looks like "odd: 0 5 9 7 1 3 0 0 0"
If I (for instance) say that "0" is an odd number I cannot print it because it gets filtered. How do I fix that?
using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { int[] numbers = Array.ConvertAll(Console.ReadLine().Split(" "), Convert.ToInt32); int uitkomst = 0; int[] numbers_odd = new int[numbers.Length]; int[] numbers_even = new int[numbers.Length]; for (int repeat = 0; repeat < numbers.Length; repeat++) { uitkomst = numbers[repeat] % 2; //Console.WriteLine(uitkomst); if(uitkomst == 1) // ODD { numbers_odd[repeat] = numbers[repeat]; //Console.WriteLine(numbers_odd[repeat]); } if (uitkomst == 0) // Even { numbers_even[repeat] = numbers[repeat]; //Console.WriteLine(numbers_even[repeat]); } } Console.Write("even: "); foreach (int item in numbers_even) { if(item == 0) { } else { Console.Write(item + " "); } } Console.WriteLine(" "); Console.Write("odd: "); foreach (int item in numbers_odd) { if (item == 0) { } else { Console.Write(item + " "); } } } } }
int []is initialized with zeros. You actually only sets some indexes, not all, that's why you have zeroes at some places