C program to place even numbers at even index and odd numbers at odd index

In this blog post, we learn how to write a C program to place even numbers at even index and odd numbers at odd index? So here we will write the C program to place even numbers at even index and odd numbers at odd index. We will also see how to place even numbers at the even index and odd numbers at the odd index of a given array using C language.

So let’s see the logic to calculate the sum of the array elements. Suppose arr is an integer array of size N (arr[N] ), the task is to write the C program to arrange the numbers in such a way that all the even numbers get the even index and odd numbers get the odd index.

Examples,

Input1 : arr[] = {1, 6, 12, 3, 7, 8}
Output1 : 6 1 12 3 8 7 



Input2 : arr[] = {4, 9, 9, 18, 13, 17, 4, 20, 23, 14}
Output2 : 4 9 18 9 20 17 4 13 14 23

 

Logic to place even numbers at even index and odd numbers at odd index:

1. Create two intermediate variables evenIndex and oddIndex.

2. Initialize the evenIndex and oddIndex variable with 0 and 1.

3. Start from the left and keep two indexes one for even position and the other for odd positions. Traverse these indexes from the left.

4. At an even position, there should be an even number and at odd positions, there should be an odd number.

5. Whenever there is a mismatch, we swap the values at odd and even index.

 

C program to place even numbers at even index and odd numbers at odd index:

#include <stdio.h>

//Calculate array size
#define ARRAY_SIZE(a)  sizeof(a)/sizeof(a[0])


void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

// function to arrange odd and even numbers
void arrangeOddAndEven(int arr[], const int n)
{
    int evenIndex = 0;
    int oddIndex = 1;

    while (1)
    {
        while (evenIndex < n && arr[evenIndex] % 2 == 0)
        {
            evenIndex += 2;
        }
        while (oddIndex < n && arr[oddIndex] % 2 == 1)
        {
            oddIndex += 2;
        }

        if (evenIndex < n && oddIndex < n)
        {
            swap(&arr[evenIndex],&arr[oddIndex]);
        }
        else
        {
            break;
        }
    }
}


int main()
{
    int arr[] = {1, 6, 12, 3, 7, 8};
    int i = 0;

    //Get array size
    const int N = ARRAY_SIZE(arr);

    arrangeOddAndEven(arr, N);

    printf("Array after segregation ");
    for (i = 0; i < N; i++)
    {
        printf("%d ", arr[i]);
    }
    return 0;
}

Output:

place even numbers at even index and odd numbers at odd index

 

 

Recommended Articles for you:

Leave a Reply

Your email address will not be published. Required fields are marked *