C Program to Count Even and Odd Elements in an Array

In this article, you will learn and get code about how to create a program in C that reads elements (numbers) from the user (at run-time) as input and counts all the even and odd elements in a given array.

The question is, "Write a program in C to read 10 elements in an array and count all even and odd elements." The answer to this question is:

#include<stdio.h>
#include<conio.h>
int main()
{
    int arr[10], evenCount=0, oddCount=0, i;
    printf("Enter any 10 elements: ");
    for(i=0; i<10; i++)
        scanf("%d", &arr[i]);
    for(i=0; i<10; i++)
    {
        if(arr[i]%2==0)
            evenCount++;
        else
            oddCount++;
    }
    printf("\nTotal Even numbers = %d", evenCount);
    printf("\nTotal Odd numbers = %d", oddCount);
    getch();
    return 0;
}

As the program was written in the Code::Blocks IDE, here is the first snapshot of the sample run:

c program count even odd numbers

Supply any 10 array elements (numbers) and then press the ENTER key to count and print the total number of even and odd numbers among all the given 10 numbers, as shown in the second snapshot of the sample run given below:

count even odd numbers c

Program Explained

  • Receive any 10 numbers (10 elements for the array) as input.
  • Create a for loop that runs 10 times, starting from 0 to 9, as indexing in an array starts with 0.
  • Inside the for loop, check whether the current element (a number) is an even or an odd number.
  • If it is an even number, then increment the evenCount variable; otherwise, increment the oddCount variable.
  • Here evenCount represents the total number of even numbers, and oddCount represents the total number of odd numbers.
  • Never forget to initialize these two variables with 0 before entering the for loop to check and increment the corresponding variable's value by one each time.
  • After checking for each and every element of the array, come out of the loop and print the value of both variables.

C Quiz


« Previous Program Next Program »


Follow/Like Us on Facebook


Subscribe Us on YouTube