Mar 31, 2017 at 8:21am Mar 31, 2017 at 8:21am UTC
You can omit the if on line 5 due to i++ and ++i.
The problem is line 3:
i> 10
change to
i< 10
Line 7 is a problem because of the order of evaluation. If ++i is evaluated first and then the value is assigned the value will not be changed. Better this:
1 2 3 4
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
++i; // Put ++i here
Last edited on Mar 31, 2017 at 8:33am Mar 31, 2017 at 8:33am UTC
Mar 31, 2017 at 5:22pm Mar 31, 2017 at 5:22pm UTC
do you need the %2?
for(I = 2; I < 10; I+=2) //2&3 swap, 4&5 swap, ... is this what you need?
//what about 0&1?
{
tmp = a[I];
a[I] = a[I+1];
a[I+1] = tmp;
}
note that this assumes an odd input array size, if your array is size 10 it will crash on swapping 10&11
Last edited on Mar 31, 2017 at 5:23pm Mar 31, 2017 at 5:23pm UTC
Apr 1, 2017 at 2:22am Apr 1, 2017 at 2:22am UTC
A more fundamental problem is here:
void swap(int a[])
even though a appears to be defined as an array, the declaration is "adjusted" to a pointer to the element type,
http://stackoverflow.com/questions/31346940/passing-array-as-function-parameter-in-c
try something like this instead:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <iostream>
#include <utility>
void swapEvenOdd(int a[], const size_t n)
{
if (n%2)
{
for (auto i = 0; i < n - 1; i += 2 )
{
std::swap (a[i], a[i+1]);
}
}
else
{
for (auto i = 0; i < n; i += 2 )
{
std::swap (a[i], a[i+1]);
}
}
for (auto i = 0; i <n; ++i)std::cout << a[i] << " " ;
}
int main()
{
int a[] = {1, 2, 3, 4, 5, 6};
swapEvenOdd(a, sizeof (a)/sizeof (a[0]));
std::cout << "\n" ;
int b[] = {1, 2, 3, 4, 5, 6, 7};
swapEvenOdd(b, sizeof (b)/sizeof (b[0]));
}
Last edited on Apr 1, 2017 at 2:23am Apr 1, 2017 at 2:23am UTC