/* can any 1 tell me wats the problem."Que: reverse an array without using temporary array " This works for N =5 but when N =6 it displays the original values of an array. */

``````#include <stdio.h>
#include <conio.h>
#define N 6
void print(int b[N])
{
int i;
printf("\n");
for(i=0;i<N;i++)
{
printf("%3d",b[i]);
}
}
void swap(int a[N])
{
int i,j;
for(i=0,j=N-1;i<N,j>=0;i++,j--)
{
if(i!=j)
{//swapping
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
else
{
break;
}
}
}
{
int i;
for(i=0;i<N;i++)
{
printf("\n [%d] : ",i+1);
scanf("%d",&b[i]);
}

}
void main()
{
int a[N],i,j;
clrscr();
print(a);
swap(a);
print(a);
getch();
}``````

`i` and `j` will never be equal when the item count is even. You're swapping both halves of the array in that case, which ultimately produces the original sequence. Perhaps instead of using that weird logic for your swapping loop, just use the relationship of `i` and `j` as the primary condition:

``````void swap(int a[N])
{
int i, j;

for (i = 0, j = N - 1; i < j; i++, j--)
{
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}``````

dev90:
There's mistake in your logic:--it will also not work for N=2,4 i.e, even numbers. because for N=6 when
i=0 j=5,
i=1,j=4,
1=2,j=3,
i=3,j=2,
i=4,j=1,
i=5 j=1,
what is been seen here is that the array elements are swaped twice for the first half half part, array is reversed and for the next half part it is reversed again making it original array.

@cse.avinash: i think Narue already explained that! You said nothing new!

NP:- yep I saw it later when I ve done my research on that question and given my time , so I thought to post what i see otherwise i would not ve posted it, and that's why I didn't post the code as it is similar to that of Narue's post.

Thanks Mr.Narue and Mr.avinash
ihavnt thought dat bt i've solved it in sm code of mine giving condition (i<j)
as outer loof of FOR.

bt usr logic is better and now i understand my mistake.
so thank you 1nce again......

Dude, this isn't twitter; spell your words properly. Even native English speakers would have trouble translating that gibberish, and Daniweb has many members who aren't native speakers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.