The following code shows you how to find even ad odd numbers from an array, and also separating both numbers from main array to evenArray and oddArray and display them on console.
Code
public static void Main(string[] args)
{
int[] arr = { 2, 3, 1, 5, 6, 4, 7, 8, 9, 11, 10 };
int size = arr.Length;
evenOddElements(arr,size);
}
// Function returns total even numbers in array
public int evenTell(int[] arr, int size)
{
int even = 0;
for (int i = 0; i < size; i++)
{
if (arr[i] % 2 == 0)
even++;
}
return even;
}
// Function returns total odd numbers in array
public int oddTell(int[] arr, int size)
{
int odd = 0;
for (int i = 0; i < size; i++)
{
if (arr[i] % 2 != 0)
odd++;
}
return odd;
}
public void evenOddElements(int[] arr, int size)
{
int j = evenTell(arr, size);
int k = oddTell(arr, size);
int[] evenArr = new int[j]; // creating array of even numbers
int[] oddArr = new int[k]; // creating array of odd numbers
int temp = 0, temp1 = 0;
for (int i = 0; i < size; i++)
{
if (arr[i] % 2 == 0)
{
evenArr[temp] = arr[i];
temp++;
}
else
{
oddArr[temp1] = arr[i];
temp1++;
}
}
Console.WriteLine("Even Array Elements Are : " + j);
for (int i = 0; i < evenArr.Length; i++)
Console.Write(evenArr[i] + " ");
Console.WriteLine();
Console.WriteLine("ODD Array Elements Are : " + k);
for (int i = 0; i < oddArr.Length; i++)
Console.Write(oddArr[i] + " ");
}
Output of the program is:
Even Array Elements Are : 5
2 4 6 8 10
ODD Array Elements Is :6
3 1 5 7 9 11
0 comments:
Post a Comment