A question!

QUESTION IS

Write a function in C++ which accepts an integer array and its size as
arguments/parameters and exchanges the values of first half side elements with the
second half side elements of the array. 3
Example:
If an array of eight elements has initial content as
2,4,1,6,7,9,23,10
The function should rearrange the array as
7,9,23,10,2,4,1,6



I wrote a code pls check this....


#include<iostream.h>
#include<conio.h>

void main()
{ clrscr();

int a[10], temp,i=0;
for( i=0;i<10;i++)
{ cout<<" Enter Value for "<<i+1<<" element: ";
cin>>a[i];
}

for( i=0; i<5;i++)
{ temp=a[i];
a[i]=a[10-i];
a[10-i]=temp;
}
cout<<"Array: ";
for(i=0;i<10;i++)
{ cout<<" "<<a[i];
}

getch();
}



I think its correct but the output doesn't changes the a[0] value! I don't know why!

I know I didn't made a function as demanded by question I am Just testing so never mind that please....
Last edited on
One problem you have is where you refer to a[ 10 - i ] and i == 0, that's an invalid index into the array "a": The indices are from 0 to 9.
1
2
3
4
5
for( i=0; i<5;i++)
{ temp=a[i];
a[i]=a[9-i];
a[9-i]=temp;
}

Array size is 10, so index is between 0 and 9.
Oh got it...
Thanks
I rewrote it like this.. the question demands this..

#include<iostream.h>
#include<conio.h>

void main()
{ clrscr();

int a[10], temp,i=0;
for( i=0;i<10;i++)
{ cout<<" Enter Value for "<<i+1<<" element: ";
cin>>a[i];
}

for( i=0; i<5;i++)
{ temp=a[i];
a[i]=a[5+i];
a[5+i]=temp;
}
cout<<"Array: ";
for(i=0;i<10;i++)
{ cout<<" "<<a[i];
}

getch();
}


thanks
Topic archived. No new replies allowed.