How to separate even and odd numbers in an array by using for loop in C language?

In C programming, separating even and odd numbers from an array is a common operation that involves checking each element's divisibility by 2. This process uses the modulus operator (%) to determine if a number leaves a remainder when divided by 2.

Syntax

// Check if number is even
if (number % 2 == 0) {
    // number is even
}

// Check if number is odd  
if (number % 2 != 0) {
    // number is odd
}

Algorithm

The logic to separate even and odd numbers involves these steps −

  1. Traverse the array using a for loop
  2. Check each element using modulus operator (%)
  3. If array[i] % 2 == 0, store in even array
  4. If array[i] % 2 != 0, store in odd array
  5. Display both arrays separately

Example: Complete Program

Here's a complete C program that separates even and odd numbers from an array −

#include <stdio.h>

void display(int arr[], int size) {
    for(int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("<br>");
}

int main() {
    int arr[] = {23, 45, 67, 12, 34, 18, 9, 56};
    int size = sizeof(arr) / sizeof(arr[0]);
    int even[20], odd[20];
    int evenCount = 0, oddCount = 0;
    
    printf("Original array: ");
    display(arr, size);
    
    /* Separate even and odd numbers */
    for(int i = 0; i < size; i++) {
        if(arr[i] % 2 == 0) {
            even[evenCount] = arr[i];
            evenCount++;
        } else {
            odd[oddCount] = arr[i];
            oddCount++;
        }
    }
    
    /* Display results */
    printf("Even numbers (%d elements): ", evenCount);
    display(even, evenCount);
    
    printf("Odd numbers (%d elements): ", oddCount);
    display(odd, oddCount);
    
    return 0;
}
Original array: 23 45 67 12 34 18 9 56 
Even numbers (4 elements): 12 34 18 56 
Odd numbers (4 elements): 23 45 67 9 

How It Works

  • Modulus Operator (%): Returns the remainder after division
  • Even Check: number % 2 == 0 means no remainder when divided by 2
  • Odd Check: number % 2 != 0 means remainder exists when divided by 2
  • Separate Arrays: Store even and odd numbers in different arrays with counters

Key Points

  • The time complexity is O(n) where n is the array size
  • Space complexity is O(n) for storing separate arrays
  • The modulus operator is the most efficient way to check even/odd
  • Always initialize counters to 0 before separation

Conclusion

Separating even and odd numbers using for loops in C is straightforward with the modulus operator. This technique is fundamental for array manipulation and helps understand conditional logic with loops.

Updated on: 2026-03-15T13:51:53+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements