+ 1
Why isn't that code flipping an array?
#include <stdio.h> #include <stdlib.h> int main() { int m [6]={1,2,3,4,5,6}; int i=0; int h; int y; int k =0; int length =sizeof(m)/sizeof(int); for(i=0,y=length;y>0;i++,y--){ //for(y=length;y>0;i--){ //while h=m[i]; m[i]=m[y]; m[y]=h; } printf("\nResult of an Reverse array is: "); for (k = 0; k < length; k++) { printf("%d", m[k]); } }
1 Answer
+ 1
Here is a corrected version of your code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m [6]={1,2,3,4,5,6};
int i=0;
int h;
int y;
int k =0;
int length =sizeof(m)/sizeof(int);
for(i=0,y=length - 1; y>= length / 2; i++,y--)
{
h=m[i];
m[i]=m[y];
m[y]=h;
}
printf("\nResult of an Reverse array is: ");
for (k = 0; k < length; k++)
{
if (k != 0)
{
printf(", ");
}
printf("%d", m[k]);
}
}
Here are a few of your mistakes.
- In your first loop, y must not start at length. It must be length - 1 since you read its value m[y]. Reading m[length] is 1 element passed the end of the array and risks anything from a memory access violation to merely reading a value you never set.
- The first loop loops i from 0 to length when it should loop over only half of it. After looping past the half way mark, you start swapping the same pairs again and restoring their original values.
- This is pretty minor but I thought you'd want commas or spaces to separate the numbers when you print them out in the second loop.