- #1

Saitama

- 4,243

- 93

## Homework Statement

Write a program to read an array of elements and interchange each element with the next one in the following manner:-

Example:-

**Input:**1 2 3 4 5

**Output:**21435

## Homework Equations

## The Attempt at a Solution

I have almost reached the solution but i am still getting some problems. Here's my program:

Code:

```
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int x[20],n,i;
cout<<"How many numbers you want to enter?";
cin>>n;
cout<<endl;
cout<<"Now enter "<<n<<" elements: \n";
for(i=0;i<n;i++)
cin>>x[i];
int tmp;
for(i=0;i<=(n/2);i+=2)
{
tmp=x[i];
x[i]=x[i+1];
x[i+1]=tmp;
}
for(i=0;i<n;i++)
cout<<x[i];
getch();
}
```

Now the problem is if i put a value of more than 5 the program does not give the resulted output.

For example, if 6 elements are entered, 1, 2, 3, 4, 5, 6, then according to the question the output should be 214365, but i don't get this output using my program.

For that i changed the second for loop, for(i=0;i<=n/2+1;i+=2), i got the correct answer for six elements but for 8 elements it again went wrong.

Can somebody please help me out?

I have been screeching my head on this problem for hours.

Thanks!