Count the odd and even elements in the given array.

Before get started with this problem, kindly refer the odd or even problem (without array) using the below link,

Odd or even - Normal method
Odd or even - Bitwise method



Problem statement

Count number of even and odd elements in an array

Input

array size = 5

Elements = { 10, 2, 3, 7, 12}

Output

Odd numbers count = 3 (i.e. 10,2,12)

Even numbers count = 2 (i.e. 3,7)

Input

array size = 4

Elements = {12, 4, 0, 8}

Output

Odd numbers count = 0

Even numbers count = 4 (i.e. 12,4,0,8)

Procedure

1.Declare two integer variables to store odd and even numbers count and initialize them to zero.

int odd_count = 0, even_count = 0;

2.Loop through each element of an array and check whether its odd or even

3.if it's odd, increment the odd_count variable by 1

4.else, increment the even_count variable by 1




Odd and even number count in the array

Normal Method


Example

#include<stdio.h>

int main()
{
    //let's assume the maximum arr size as 100.
    int arr[100], size, odd_count = 0, even_count = 0, i;

    //get array size from the user
    printf("Enter array size\n");
    scanf("%d",&size);

    //get array elements from the user
    printf("Enter array elements\n");
    for(i = 0; i < size; i++)
          scanf("%d",&arr[i]);

    /*check each element in the array
     *if its odd, increment odd count
     *else, increment even count
     */

    for(i = 0; i < size; i++)
    {
        if(arr[i] % 2 == 1)
            odd_count++;
        else
            even_count++;
    }

    //print the result
    printf("Odd number count = %d\nEven number count = %d\n",odd_count,even_count);

    return 0;
}



Bitwise Method


Example

#include<stdio.h>

int main()
{
    //let's assume the maximum arr size as 100.
    int arr[100], size, odd_count = 0, even_count = 0, i;

    //get array size from the user
    printf("Enter array size\n");
    scanf("%d",&size);

    //get array elements from the user
    printf("Enter array elements\n");
    for(i = 0; i < size; i++)
          scanf("%d",&arr[i]);

    /*check each element in the array
     *if its odd, increment odd count
     *else, increment even count
     */

    for(i = 0; i < size; i++)
    {
        if(arr[i] & 1 == 1)
            odd_count++;
        else
            even_count++;
    }

    //print the result
    printf("Odd number count = %d\nEven number count = %d\n",odd_count,even_count);

    return 0;
}

Bitwise solution is more efficient way to solve the above problem.


Topics You Might Like