C program to count even and odd elements in an array

Write a C program to read elements in an array from user and count total number of even and odd elements in the given array. How to find total number of even and odd elements in a given array using C programming. Logic to find even and odd elements in an array.

Example:
Input array: 1 2 3 4 5 6 7 8 9
Output:
Total even elements: 4
Total odd elements: 5

Required knowledge

Basic C programming, If else, Loop, Array

Logic to count total even/odd elements in array

Counting total number of even odd is a very simple process. You just need to have a good understanding of even/odd numbers and checking even/odd numbers in C programming. Apart from that you must know how to iterate through the array elements using loops.
Below is a basic logic to count total even or odd elements in an array.
  1. Run a loop from the starting to end index of the array 0-N (Where N is the total number of elements in array).
  2. Check the current element of array. If it is even then, increment the even count by 1. Otherwise increment the odd count.
  3. Print the values of even and odd after the termination of loop.
And you are done.

Program to count total even/odd elements in array

/**
 * C program to count total number of even and odd elements in an array
 */

#include <stdio.h>

#define MAX_SIZE 100 //Maximum size of the array

int main()
{
    int arr[MAX_SIZE];
    int i, N, even, odd;

    /*
     * Reads size and elements in array
     */
    printf("Enter size of the array: ");
    scanf("%d", &N);
    printf("Enter %d elements in array: ", N);
    for(i=0; i<N; i++)
    {
        scanf("%d", &arr[i]);
    }

    /* Assuming that there are 0 even and odd elements */
    even = 0;
    odd  = 0;

    for(i=0; i<N; i++)
    {
        /* If the current element of array is even then increment even count */
        if(arr[i]%2 == 0)
        {
            even++;
        }
        else
        {
            odd++;
        }
    }

    printf("Total even elements: %d\n", even);
    printf("Total odd elements: %d\n", odd);

    return 0;
}


Output
Enter size of the array: 10
Enter 10 elements in array: 5 6 4 12 19 121 1 7 9 63
Total even elements: 3
Total odd elements: 7

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment