Write a C# program to input elements in array from user and count even and odd elements in array.
How to find total number of even and odd elements in a given array using C# programming. Logic to count even and odd elements in array using loops.
Step by step descriptive logic to count total even and odd elements in array.
- Input size and elements in array from user. Store it in some variable say size and arr.
- Declare and initialize two variables with zero to store even and odd count.
- Iterate through each array element. Run a loop from 0 to size – 1. Loop structure should look like for(i=0; i<size; i++).
- Inside loop increment even count by 1 if current array element is even. Otherwise increment the odd count.
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) { //C program to count total number of even and odd elements in an array int size, even, odd; int[] arr; //Input size of the array Console.Write("Enter size of the array: "); size = Convert.ToInt32(Console.ReadLine()); //Input array elements Console.WriteLine("Enter {0} elements in array:", size); arr = new int[size]; for (int i = 0; i < size; i++) { Console.Write("Number({0}) :", i+1); arr[i] = Convert.ToInt32(Console.ReadLine()); } //Assuming that there are 0 even and odd elements even = 0; odd = 0; for (int i = 0; i < size; i++) { //If the current element of array is even then increment even count if (arr[i] % 2 == 0) { even++; } else { odd++; } } Console.Write("Total even elements: {0}\n", even); Console.Write("Total odd elements: {0}", odd); Console.ReadLine(); } } |
Code Output: