Outer to Inner Swap – Both Odd/Even
Swap elements from outer positions to inner positions if both elements are odd or both are even
Understand the Problem
Problem Statement
Given N numbers, the program must swap the first and last element, swap 2nd and last but one element and so on if both the elements are odd or even. If N is odd, the swap will not occur for the middle element.
Constraints
- 2 ≤ N ≤ 9999
- Value of a given number is from 1 to 99999
- Array elements must be positive integers
- Only swap if both elements have same parity (both odd or both even)
Examples
7
4 11 17 6 11 18 22 11 11 6 17 18 4Take 4 and 2. Swap occurs as both are even. Now 11 and 18, no swap as 11 is odd and 18 is even. Now consider the pair 17 and 11. Swap occurs as both are odd. 6 is middle element (as N is odd) and hence retained as it is.
4
2 4 6 88 6 4 2All elements are even, so all pairs will be swapped: 2↔8 and 4↔6
6
1 3 5 7 9 1111 9 7 5 3 1All elements are odd, so all pairs will be swapped: 1↔11, 3↔9, and 5↔7
Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d", &n);
int a[n];
int i, j = 0, k = n - 1, temp;
// Read input array
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
// Swap elements from outer to inner if both have same parity
for (i = 0; i < n / 2; i++)
{
if ((a[k] % 2 == 0 && a[j] % 2 == 0) || (a[k] % 2 != 0 && a[j] % 2 != 0))
{
// Swap elements
temp = a[k];
a[k] = a[j];
a[j] = temp;
}
k--;
j++;
}
// Print the result
for (i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}Step-by-step explanation:
- Read the number of elements N
- Declare and read the array of size N
- Initialize two pointers: j=0 (start) and k=n-1 (end)
- Loop through the first half of the array (i < n/2)
- For each pair, check if both elements have same parity using modulo operator
- If both are even (a[k]%2==0 && a[j]%2==0) OR both are odd (a[k]%2!=0 && a[j]%2!=0), swap them
- Move pointers: increment j, decrement k
- After loop, print the modified array
The middle element (if N is odd) is automatically left untouched since we only iterate through n/2 positions.