C is a general-purpose language which is specially used to create operating systems due to its portability and low-level access to memory. From this article, we will be extracting the odd and even numbers from an array and display their respective count using C.

Odd & Even Numbers in an Array using C

As we are creating an array, either we can hardcode the size and data that need to be included in the array in the code itself, or we can customize it by giving the user to decide the size and elements that should be included in the array. In this post, we’ll be talking about both these methods. To start on with this, let’s create an array called numbers which takes only integer values.

Method 1: Array is created and initialized inside the code

int numbers[6] = {12, 45, 67, 34, 3, 8};

Array size is fixed and cannot be changed after initializing the array.

Method 2: The user decides array size and elements

int numbers[6], size;
printf("Enter the array size: \n");
scanf("%d", &size);

printf("Array Elements: \n");
for (i = 0; i < size; i++) {
      scanf("%d", &numbers[i]);
}

In here, the array with size six is defined, and the user can use any size less than or equal to that of the specified size. “%d” is typically used to take the next argument in the array as an integer. After size is defined, we iterate through the array and add elements to it. In C, we always point to the address of the value using “&”.

Hence, in this article, we are going to use method 2 to insert the elements to the array. The primary aim of this is to count the odd numbers and even numbers in the array. For this, we’ll be using the modulus (%) operator. Any number which is divisible by two without any remainder is said to be an even number, and remaining ones are odd numbers.

#include <stdio.h>

int main()
{
        int numbers[100], size, evenCount = 0, oddCount = 0;
        printf("Enter the array size: \n");
        scanf("%d", &size);

        printf("Array Elements: \n");
        for (int i = 0; i < size; i++) 
        {
            scanf("%d", &numbers[i]);
        }

        for (int j = 0; j < size; j++) 
        {
            if (numbers[j] % 2 == 0) 
            {
                evenCount++;
            }
            else {
                oddCount++;
            }
        }
       printf("Even Number Count:%d \t", evenCount);
       printf("Odd Number Count:%d \t", oddCount);
    return 0;
}

In here, we have declared two variables, evenCount, and oddCount to hold the number count and by iterating through the array, we check whether that number is divisible by two without any remainder or not and increment the counts based on the results of the particular condition. After terminating the loop, results are shown using the printf method.

Result

Related Articles

Last modified: March 15, 2019

Comments

Write a Reply or Comment

Your email address will not be published.