Swap Even Integers Pair
Swap every pair of even integers in an array while keeping odd integers unchanged
Understand the Problem
Problem Statement
Problem Statement
The program must accept N integers as the input. The program swap every two even integers among the N integers. Then the program must print the N modified integers as the output. If the number of even integers is odd, the last even integer will remain the same as it has no pair to swap.
Constraints
Constraints
- 2 ≤ N ≤ 1000
- 1 ≤ Each integer value ≤ 10⁵
Examples
7
22 43 56 51 68 50 2856 43 22 51 50 68 28There are two even integer pairs in the given integers. The first even integer pair is 22 and 56. After swapping, the integers become 56 43 22 51 68 50 28. The second even integer pair is 68 and 50. After swapping, the integers become 56 43 22 51 50 68 28.
6
2 8 3 12 98 568 2 3 98 12 56The even integer pairs are (2,8) and (12,98). After swapping: (8,2) and (98,12). The odd integer 3 remains unchanged.
Solution
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int count = 0;
int firstEvenIndex = -1;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
count++;
if (count == 2) {
// Swap the pair
int temp = arr[firstEvenIndex];
arr[firstEvenIndex] = arr[i];
arr[i] = temp;
count = 0;
}
firstEvenIndex = i;
}
}
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}Step-by-step explanation:
- Input Reading: Read N and then read N integers into an array
- Tracking Variables: Use
countto track even integers in current pair (0, 1, or 2), andfirstEvenIndexto store position of first even integer in pair - Pair Detection: When encountering an even integer:
- If it's the first even integer (count = 1), just store its index
- If it's the second even integer (count = 2), swap it with the first even integer and reset count to 0
- Output: Print the modified array
The algorithm handles the case where there's an odd number of even integers naturally - the last even integer will have count = 1 but no second even integer to pair with, so it remains unchanged.