ronith
5/29/2018 - 8:16 PM

Even numbers at even index and odd numbers at odd index

#include<iostream>
using namespace std;

int check(int a[], int n, int i){
    if (i%2 == 0){
        for (int j = i+1; j < n;j+= 2)
            if (a[j]%2 == 0)
                return j;
    }
    else{
        for (int j = i+1; j < n;j+= 2)
            if (a[j]%2 == 1)
                return j;
    }
}

int main(){
    int n;
    cout << "Enter the no.of elements:";
    cin >> n;
    int a[n];
    cout << "Enter the elements:\n";
    for (int i = 0;i < n;i++)
        cin >> a[i];

    for (int i = 0; i < n; i++){
        if ((i%2 == 0 && a[i]%2 == 0) || (i%2 == 1 && a[i]%2 == 1))
            continue;
        if ((i%2 == 0 && a[i]%2 == 1)){
            int j = check(a, n, i);
            swap(a[i],a[j]);
        }
        if ((i%2 == 1 && a[i]%2 == 0)){
            int j = check(a, n, i);
            swap(a[i],a[j]);
        }
    }
    for (int i = 0;i < n;i++)
        cout << a[i] << "  ";
}