Q:

Write C# program to count even and odd elements in an array

0

Write C# program to count even and odd elements in an array

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

I have used Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability.

using System;
class Program
{
    static void Main()
    {       
        int[] arr = new int[100];
        int i, num, evennum, oddnum;
 
        ////Reads size and elements in array
        Console.WriteLine("Enter size of the array: ");
        num = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter "+num+" elements in the array: ");  
 
        for(i=0; i<num; i++)
        {
            arr[i] = Convert.ToInt32(Console.ReadLine());            
        }
 
        evennum = 0; // Assuming 0 even numbers
        oddnum = 0; // Assuming 0 odd numbers
 
        for (i = 0; i < num; i++)
        {
            /* If the current element of array is evennumber then increment evennumber count */
            if (arr[i] % 2 == 0)
            {
                evennum++;
            }
            else
            {
                oddnum++; // increment oddnumber count
            }
        }
 
        Console.WriteLine("Total even  numbers: "+evennum);
        Console.WriteLine("Total odd numbers: " + oddnum);
 
 
        Console.ReadLine();
    }
 
}

Result:

Enter size of the array: 

5

Enter 5 elements in the array: 

1

2

3

4

5

Total even  numbers: 2

Total odd numbers: 3

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Write C# program to insert an element in array... >>
<< Write C# program to find sum of all elements of an...