• Support PF! Buy your school textbooks, materials and every day products Here!

Array question (C++)

  • Comp Sci
  • Thread starter Saitama
  • Start date
  • #1
3,812
92

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? :smile:

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

Answers and Replies

  • #2
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
683
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.
 
  • #3
3,812
92
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.
 
  • #4
jtbell
Mentor
15,518
3,353
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:
  • #5
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
683
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.
 
  • #6
3,812
92
Thank you for the help! :smile:
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.
 
  • #7
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
683
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?
 
  • #8
3,812
92
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? :confused:

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? :confused:
 
  • #9
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
683
Have you tried my suggestion of hand-executing your code? It's not at all hard in this case.
 
  • #10
3,812
92
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.
 
  • #11
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
683
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.
 
  • #12
jtbell
Mentor
15,518
3,353
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.
 
  • #13
760
69
This doesn't address the OP's issue but it is important. These lines are not correct:

Code:
#include<iostream.h>
Code:
void main()
instead they should be

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 recieving improper instruction on these matters.
 
  • #14
3,812
92
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? :confused:

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

Code:
#include<iostream.h>
Code:
void main()
instead they should be

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 recieving improper instruction on these matters.
I have already asked this question before to my teacher. :smile:
In India, C++ students are taught on an ancient version of Turbo C++ (which looks something like DOS :biggrin:)

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. :smile:
 
  • #15
Borek
Mentor
28,357
2,745
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? :confused:
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.
 
  • #16
3,812
92
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]?
 
  • #17
Borek
Mentor
28,357
2,745
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.
 
  • #18
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
683
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:
  • #19
I like Serena
Homework Helper
6,577
176
So what should i do now?
Do you mean that "junk" gets swapped with the value of x[6]?
Try your original program with:
for(i=0;i<n-1;i+=2)
 
  • #20
3,812
92
Try your original program with:
for(i=0;i<n-1;i+=2)
Thanks for your help I like Serena!
The program is working perfectly now. :smile:
 
  • #21
I like Serena
Homework Helper
6,577
176
Hey Pranav-Arora! :wink:

Do you understand why it works now?
 
  • #22
3,812
92
Hey Pranav-Arora! :wink:

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. :smile:
 
  • #23
I like Serena
Homework Helper
6,577
176
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. :smile:
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...
 
  • #24
3,812
92
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. :smile:

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();
}
 
  • #25
I like Serena
Homework Helper
6,577
176
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?
 

Related Threads on Array question (C++)

Replies
3
Views
1K
  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
4
Views
2K
  • Last Post
Replies
12
Views
2K
  • Last Post
Replies
5
Views
2K
  • Last Post
Replies
4
Views
14K
Replies
8
Views
3K
Replies
16
Views
4K
  • Last Post
Replies
20
Views
3K
Top