C# program to separate odd and even numbers in array.
In this example, we will get 10 numbers from the user. We will calculate the number of odd and even numbers among the received numbers.
Output:
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
class Program { static void Main(string[] args) { int[] numbers = new int[10]; int oddCount = 0; int evenCount = 0; for (int i = 0; i < numbers.Length; i++) { Console.Write("Enter a number: "); numbers[i] = Convert.ToInt32(Console.ReadLine()); if (numbers[i] % 2 != 0) oddCount++; else evenCount++; } //Store odd numbers into an array int[] oddNumbers = new int[oddCount]; int[] evenNumbers = new int[evenCount]; for (int i = 0; i < numbers.Length; i++) { if (numbers[i] % 2 != 0) oddNumbers[--oddCount] = numbers[i]; else evenNumbers[--evenCount]= numbers[i]; } Console.WriteLine("\nOdd Numbers:"); for (int i = 0; i < oddNumbers.Length; i++) { Console.Write(oddNumbers[i] + " "); } Console.WriteLine("\nEven Numbers:"); for (int i = 0; i < evenNumbers.Length; i++) { Console.Write(evenNumbers[i] + " "); } Console.ReadLine(); } } |