Array question (C++)

  • Comp Sci
  • Thread starter Saitama
  • Start date
  • #1
3,816
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? :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,415
687
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,816
93
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,870
4,493
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,415
687
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,816
93
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,415
687
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,816
93
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,415
687
Have you tried my suggestion of hand-executing your code? It's not at all hard in this case.
 
  • #10
3,816
93
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,415
687
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,870
4,493
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
764
71
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,816
93
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,976
3,608
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,816
93
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,976
3,608
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,415
687
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,579
179
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,816
93
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,579
179
Hey Pranav-Arora! :wink:

Do you understand why it works now?
 
  • #22
3,816
93
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,579
179
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,816
93
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,579
179
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?
 
  • #26
3,816
93
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. :smile:

[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]
 
  • #27
D H
Staff Emeritus
Science Advisor
Insights Author
15,415
687
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:
  • #28
I like Serena
Homework Helper
6,579
179
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. :smile:

Darn! You're right! :wink:

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?


[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/" [Broken].

The book I recommend is "The C++ Programming Language" from Bjarne Stroustrup, who invented the language.
 
Last edited by a moderator:
  • #29
3,816
93
Darn! You're right! :wink:

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

Ah, the code misbehaves at n=7. :redface:

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/" [Broken].

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. :smile:
 
Last edited by a moderator:
  • #30
I like Serena
Homework Helper
6,579
179
Thanks! :smile:

Ah, the code misbehaves at n=7. :redface:

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?

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.
 
  • #31
D H
Staff Emeritus
Science Advisor
Insights Author
15,415
687
I can recommend: http://newdata.box.sk/bx/c/" [Broken].
ars_longa_vita_brevis.PNG


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:
  • #33
I like Serena
Homework Helper
6,579
179
What's the rush? ][PLAIN]http://abstrusegoose.com/strips/ars_longa_vita_brevis.PNG[/URL][/QUOTE] [Broken]

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


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

Now, what if i=0?
Which elements will be swapped?
 
Last edited by a moderator:
  • #34
3,816
93
Good!
Now for instance with n=6 and with n=7 the proper elements will be swapped! :smile:

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. :)
 
  • #35
D H
Staff Emeritus
Science Advisor
Insights Author
15,415
687
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.
 

Related Threads on Array question (C++)

  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
4
Views
2K
  • Last Post
Replies
12
Views
2K
Replies
4
Views
2K
  • Last Post
Replies
4
Views
15K
  • Last Post
Replies
1
Views
5K
  • Last Post
Replies
20
Views
4K
Replies
3
Views
2K
  • Last Post
Replies
5
Views
914
Top