# C++ Array Interchange: Solve Homework Problem

• Comp Sci
• Saitama
In summary: So then i try x[4], x[3], x[2], x[1] and finally x[0], and it work!In summary, the problem is that the limit is incorrect.
Saitama

## 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

## 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.

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

First off, what is going wrong? You have only given a vague indication that things aren't right.

Secondly, Print the array before and after you swap it to see if the array was read in properly.

Thirdly, C++ input is a bit (more than a bit) fragile. One mistake on input and kaboom! the stream is dead. All subsequent attempts to read from the stream will also fail unless you reset the stream.

The program is running completely right.
I think the problem is somewhere here:-

for (i=0;i<=n/2;i+=2)

I should add something to n/2 but i don't understand what should be this "something"?

If you still don't understand, i explain it again:
For example, Input is 234567
Then the output should be 325476.

But my program does not print this output.
It prints 325467, which is wrong.

I suggest the following diagnostic measures:

1. Immediately before the second for-loop, insert a 'cout' statement to display the value of n/2.

2. Inside the second for-loop, insert a 'cout' statement to display the value of i.

This will give you information about whether the loop conditions are doing what you want them to do.

Also try a larger value of n, e.g. 10 or 12, to see how the problem manifests itself in those cases.

Last edited:
Walking through your code by hand is a very good debugging tool. Try executing your swapping loop by hand.
Hint #1: It misbehaves for n=0 and 1 as well as for 6 and up.

What should you be doing instead?
Hint #2: You might want to think about rewriting that loop entirely.

Thank you for the help!
I changed the code a little.

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;
if (n>=6)
{
for(i=0;i<=n;i+=2)
{
tmp=x[i];
x[i]=x[i+1];
x[i+1]=tmp;
}
}
else
{
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();
}

Everything runs fine now.
But if i enter 1, it gives 0 and if i enter 0 and press enter, the program exits.

This is perhaps overly blunt, but ...

You just committed the sin of the maintenance programmer: Come up with a kludgy fix that appears to solve the problem without thinking about the real cause of the problem. Your problem was caused by having an erroneous loop that by pure dumb luck worked for a small handful of cases.

Now you have two erroneous loops, and you are lucky you aren't getting a core dump.

That first loop is close to correct for all n, but the limit is incorrect. Walk through that loop by hand for n=6 and n=7. How many times are you swapping? How many times should you be swapping? What is the correct value for the limit?

D H said:
You just committed the sin of the maintenance programmer: Come up with a kludgy fix that appears to solve the problem without thinking about the real cause of the problem.

Lol. Sin? :rofl:
Hey hey, i am just a student in C++ and we aren't thought that much as you would be thinking of. :rofl:

Now you have two erroneous loops, and you are lucky you aren't getting a core dump.

That first loop is close to correct for all n, but the limit is incorrect. Walk through that loop by hand for n=6 and n=7. How many times are you swapping? How many times should you be swapping? What is the correct value for the limit?

Two erroneous loops? Are you talking about the first and the second for loop?
And what limit are you talking about?

Oh yeah, i found something weird while swapping when n=7.
When the swapping loop run, i reach to 6 and then i get confuse on what to do now because there nothing like x[7] in the program. So how will i swap here?

Have you tried my suggestion of hand-executing your code? It's not at all hard in this case.

D H said:
Have you tried my suggestion of hand-executing your code? It's not at all hard in this case.

Yes, i did the same hand-executing method.
And at n=7, i am not able to complete the swapping process.

So that means you shouldn't be going that far.

The same problem happens with n=6:
i=0: 0<=6, so swap x[0] w/ x[1]
i=2: 2<=6, so swap x[2] w/ x[3]
i=4: 4<=6, so swap x[4] w/ x[5]
i=6: 6<=6, so swap x[6] w/ x[7]
i=8: 8>6, so done.

You should not be swapping x[6] with x[7] here.

If n is odd, you don't want to do anything with the last item in the array, because there's nothing to swap it with.

n=1: do nothing
n=2: swap i=0&1
n=3: swap i=0&1, leave i=2 alone
n=4: swap i=0&1, swap i=2&3
n=5: swap i=0&1, swap i=2&3, leave i=4 alone
n=6: swap i=0&1, swap i=2&3, swap i=4&5
n=7: swap i=0&1, swap i=2&3, swap i=4&5, leave i=6 alone

etc.

This doesn't address the OP's issue but it is important. These lines are not correct:

Code:
#include<iostream.h>

Code:
void main()

Code:
#include<iostream>
and
Code:
int main()
repsectively

The main function should return int in C++! The head iostream.h is not part of standard C++! It is unfortunate if students are receiving improper instruction on these matters.

D H said:
So that means you shouldn't be going that far.

The same problem happens with n=6:
i=0: 0<=6, so swap x[0] w/ x[1]
i=2: 2<=6, so swap x[2] w/ x[3]
i=4: 4<=6, so swap x[4] w/ x[5]
i=6: 6<=6, so swap x[6] w/ x[7]
i=8: 8>6, so done.

You should not be swapping x[6] with x[7] here.

I did the same but when i reached i=6, i wondered what to do now because there's no value in x[7]. And since there is no value, how will i swap?

MisterX said:
This doesn't address the OP's issue but it is important. These lines are not correct:

Code:
#include<iostream.h>

Code:
void main()

Code:
#include<iostream>
and
Code:
int main()
repsectively

The main function should return int in C++! The head iostream.h is not part of standard C++! It is unfortunate if students are receiving improper instruction on these matters.

In India, C++ students are taught on an ancient version of Turbo C++ (which looks something like DOS )

We cannot use <iostream> at the place of <iostream.h>.
In my textbook, the author uses "int" at the place of "void". I wondered what's the difference? I asked my computer teacher regarding this and he said that he will tell us the difference between these two when the right time comes.

Pranav-Arora said:
I did the same but when i reached i=6, i wondered what to do now because there's no value in x[7]. And since there is no value, how will i swap?

You are using uninitialized variable - there is a value, you just have no idea what it is. It contains some junk that was present in the memory.

Borek said:
You are using uninitialized variable - there is a value, you just have no idea what it is. It contains some junk that was present in the memory.

So what should i do now?
Do you mean that "junk" gets swapped with the value of x[6]?

Pranav-Arora said:
So what should i do now?

Make sure your program doesn't touch uninitialized variable. Basically that's where you problem lies from the very beginning - you need to write a loop that behaves slightly differently for odd and even numbers of objects. See jtbell post again.

Do you mean that "junk" gets swapped with the value of x[6]?

Junk gets swapped with whatever table element your program tries to swap it. In the case you refer to - yes, x[6].

when i reached i=6, i wondered what to do now because there's no value in x[7]. And since there is no value, how will i swap?

Fact that you didn't know what value is there clearly pointed out that that's where the problem lies - your index takes incorrect value.

Borek said:
Basically that's where you problem lies from the very beginning - you need to write a loop that behaves slightly differently for odd and even numbers of objects.
The loop statement does not have to be complex, however. One size fits all will do it, and that one size fits all for statement can be very clean.

The body of the swap loop swaps array elements i and i+1. Both of these must be within the range 0 to n-1 because those are the array elements to which the input loop assigned values. In other words, that loop body must only execute when i≥0 and i≤n-1 and i+1≥0 and i+1≤n-1. If i≥0 then i+1 is necessarily ≥ 0. Similarly, if i+1≤n-1 then i is necessarily ≤ n-1. Eliminating the redundant conditions leaves i≥0 and i+1≤n-1 as the condition that must always be true (aka loop invariant) to ensure the body of the loop is accessing valid data. This invariant can easily be converted to the for loop conditional.

Last edited:
Pranav-Arora said:
So what should i do now?
Do you mean that "junk" gets swapped with the value of x[6]?

for(i=0;i<n-1;i+=2)

I like Serena said:
for(i=0;i<n-1;i+=2)

Thanks for your help I like Serena!
The program is working perfectly now.

Hey Pranav-Arora!

Do you understand why it works now?

I like Serena said:
Hey Pranav-Arora!

Do you understand why it works now?

Maybe yes, because when i did the hand-debugging process, i found that there's no problem of "junk" here.
I tested it for n=7 and 6 and it worked fine.

Pranav-Arora said:
Maybe yes, because when i did the hand-debugging process, i found that there's no problem of "junk" here.
I tested it for n=7 and 6 and it worked fine.

Did you notice I removed the divide-by-2 from your for-loop?
Do you "get" the difference?

Actually, D H explains the range of the for-loop in more detail in post #18...

I like Serena said:
Did you notice I removed the divide-by-2 from your for-loop?
Do you "get" the difference?

Actually, D H explains the range of the for-loop in more detail in post #18...

Yes, i did notice that you removed the divide-by-2 and made it n-1.

I found one more way for the same question:-
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=1;i<=n;i++)
cin>>x[i];
int tmp;
for(i=1;i<=n;i+=2)
{
tmp=x[i];
x[i]=x[i+1];
x[i+1]=tmp;
}
for(i=1;i<=n;i++)
cout<<x[i];
getch();
}

Hmm, suppose n is even, say n=6.
Then the highest index you will get inside your loop is i=6.
Which 2 elements will be exchanged then?

I like Serena said:
Hmm, suppose n is even, say n=6.
Then the highest index you will get inside your loop is i=6.
Which 2 elements will be exchanged then?

If you are asking about the code i just posted, then the 2 elements will be exchanged are x[5] and x[6].

When the swapping loop starts, the values present in x[1], x[3] and x[5] gets stored in the tmp and are exchanged. For example, value in x[1] gets exchanged with x[2], x[3] gets exchanged with x[4] and x[5] exchange with x[6]. In the swapping loop, the value of i cannot reach 6.

[offtopic]Can you suggest me some good resources for learning C++? I missed some of my C++ classes on the looping section and i had to learn for-loop on my own. :( [/offtopic]

Pranav-Arora said:
If you are asking about the code i just posted, then the 2 elements will be exchanged are x[5] and x[6].
[strike]
No, the last two elements that are exchanged are x[6] and x[7]. Look at your own code.

Does either one of those elements have an assigned value in your array?[/strike]

Edit
Ah, you are using Fortran indexing rather than C/C++. That is not a good idea.

You still have a problem though with odd n.

Last edited:
Pranav-Arora said:
If you are asking about the code i just posted, then the 2 elements will be exchanged are x[5] and x[6].

When the swapping loop starts, the values present in x[1], x[3] and x[5] gets stored in the tmp and are exchanged. For example, value in x[1] gets exchanged with x[2], x[3] gets exchanged with x[4] and x[5] exchange with x[6]. In the swapping loop, the value of i cannot reach 6.

Darn! You're right!

All right, now let's take n=7. Then the highest value "i" can and shall take inside the loop is i=7.
Which 2 elements are swapped then?
Pranav-Arora said:
[offtopic]Can you suggest me some good resources for learning C++? I missed some of my C++ classes on the looping section and i had to learn for-loop on my own. :( [/offtopic]

I can recommend: http://newdata.box.sk/bx/c/" .

The book I recommend is "The C++ Programming Language" from Bjarne Stroustrup, who invented the language.

Last edited by a moderator:
I like Serena said:
Darn! You're right!

All right, now let's take n=7. Then the highest value i can and shall take inside the loop is i=7.
Which 2 elements are swapped then?

Thanks!

Ah, the code misbehaves at n=7.

When i did the hand-debugging process, i found that i reaches 7 and gets swapped with x[8] which is nothing in the program. Moreover, when i run the code in Turbo C++ and i gave the input:- 1234567, the output results to this:- 2143650.

Lol, its zero, does that mean x[8]=0?

I can recommend: http://newdata.box.sk/bx/c/" .

The book I recommend is "The C++ Programming Language" from Bjarne Stroustrup, who invented the language.

Thanks for the suggestions ILS, i will definitely look into these books.

Last edited by a moderator:
Pranav-Arora said:
Thanks!

Ah, the code misbehaves at n=7.

When i did the hand-debugging process, i found that i reaches 7 and gets swapped with x[8] which is nothing in the program. Moreover, when i run the code in Turbo C++ and i gave the input:- 1234567, the output results to this:- 2143650.

Oops! Can you correct that?

Pranav-Arora said:
Lol, its zero, does that mean x[8]=0?

Only if you are "lucky".
If you switch off the debugging flags in Turbo C++, I expect that you'll find it is not zero, but some very weird value.

I like Serena said:
I can recommend: http://newdata.box.sk/bx/c/" .

What's the rush? http://norvig.com/21-days.html

The book I recommend is "The C++ Programming Language" from Bjarne Stroustrup, who invented the language.
That I can concur with.

Last edited by a moderator:
D H said:

Lol, that is really funny! :rofl:
I like Serena said:
Oops! Can you correct that?

The only way i found was changing the swapping loop.
for(i=1;i<=n-1;i+=2)

Last edited:
D H said:
What's the rush? ][PLAIN]http://abstrusegoose.com/strips/ars_longa_vita_brevis.PNG[/URL][/QUOTE]

I just learned that it would only take me about 20 more years to build a flux capacitor.
I already did the other stuff.
Anyone willing to help me with that?
Pranav-Arora said:
The only way i found was changing the swapping loop.
for(i=0;i<=n-1;i+=2)

Good!
Now for instance with n=6 and with n=7 the proper elements will be swapped!

Now, what if i=0?
Which elements will be swapped?

Last edited by a moderator:
I like Serena said:
Good!
Now for instance with n=6 and with n=7 the proper elements will be swapped!

Now, what if i=0?
Which elements will be swapped?

Sorry ILS, i should have written for(i=1;i<=n-1;i+=2) :shy:

In my code, "i" can never be 0. :)

Pranav-Arora said:
In my code, "i" can never be 0. :)
That's Fortran indexing, and it is best to stick with the standard idiom of the language with which you are working. C and C++ use zero based indexing.

I know you're just a student, but you may well find yourself programming during your job -- even if you aren't a programmer by name or degree. There are plenty of science and engineering based organizations that do a considerable amount of programming, and they typically hire scientists and engineers rather than CS majors to do that programming.

• Engineering and Comp Sci Homework Help
Replies
2
Views
2K
• Engineering and Comp Sci Homework Help
Replies
3
Views
742
• Engineering and Comp Sci Homework Help
Replies
18
Views
1K
• Engineering and Comp Sci Homework Help
Replies
7
Views
1K
• Engineering and Comp Sci Homework Help
Replies
2
Views
1K
• Engineering and Comp Sci Homework Help
Replies
2
Views
2K
• Engineering and Comp Sci Homework Help
Replies
21
Views
2K
• Engineering and Comp Sci Homework Help
Replies
7
Views
1K
• Engineering and Comp Sci Homework Help
Replies
8
Views
1K
• Engineering and Comp Sci Homework Help
Replies
14
Views
3K