C# program to split the Even and Odd integers into different arrays

CsharpProgrammingServer Side Programming

Take two arrays:

int[] arr2 = new int[5];
int[] arr3 = new int[5];

Now, if the array element gets the remainder 0 on dividing by 2, it is even. Get those elements and add in another array. This loops through the length of the array:

if (arr1[i] % 2 == 0) {
   arr2[j] = arr1[i];
}

In the else condition, you will get the odd elements. Add them to a separate array and display them individually as shown in the below example:

Example

 Live Demo

using System;
namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         int[] arr1 = new int[] {
            77,
            34,
            59,
            42,
            99
         };
         int[] arr2 = new int[5];
         int[] arr3 = new int[5];
         int i, j = 0, k = 0;
         for (i = 0; i < 5; i++) {
            if (arr1[i] % 2 == 0) {
               arr2[j] = arr1[i];
               j++;
            } else {
               arr3[k] = arr1[i];
               k++;
            }
         }
         Console.WriteLine("Even numbers...");
         for (i = 0; i < j; i++) {
            Console.WriteLine(arr2[i]);
         }
         Console.WriteLine("Odd numbers...");
         for (i = 0; i < k; i++) {
            Console.WriteLine(arr3[i]);
         }
      }
   }
}

Output

Even numbers...
34
42
Odd numbers...
77
59
99
raja
Published on 20-Aug-2018 13:54:41
Advertisements