1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Array question (C++)

  1. Nov 16, 2011 #1
    1. The problem statement, all variables and given/known data
    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


    2. Relevant equations



    3. The attempt at a solution

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

    #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:
     
  2. jcsd
  3. Nov 16, 2011 #2

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    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.
     
  4. Nov 16, 2011 #3
    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.
     
  5. Nov 16, 2011 #4

    jtbell

    User Avatar

    Staff: Mentor

    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: Nov 16, 2011
  6. Nov 16, 2011 #5

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    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.
     
  7. Nov 16, 2011 #6
    Thank you for the help! :smile:
    I changed the code a little.

    Code (Text):

    #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.
     
  8. Nov 16, 2011 #7

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    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?
     
  9. Nov 16, 2011 #8
    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:

    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:
     
  10. Nov 16, 2011 #9

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    Have you tried my suggestion of hand-executing your code? It's not at all hard in this case.
     
  11. Nov 16, 2011 #10
    Yes, i did the same hand-executing method.
    And at n=7, i am not able to complete the swapping process.
     
  12. Nov 16, 2011 #11

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    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.
     
  13. Nov 16, 2011 #12

    jtbell

    User Avatar

    Staff: Mentor

    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.
     
  14. Nov 16, 2011 #13
    This doesn't address the OP's issue but it is important. These lines are not correct:

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

    Code (Text):
    #include<iostream>
    and
    Code (Text):
    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.
     
  15. Nov 16, 2011 #14
    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:

    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:
     
  16. Nov 17, 2011 #15

    Borek

    User Avatar

    Staff: Mentor

    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.
     
  17. Nov 17, 2011 #16
    So what should i do now?
    Do you mean that "junk" gets swapped with the value of x[6]?
     
  18. Nov 17, 2011 #17

    Borek

    User Avatar

    Staff: Mentor

    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.

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

    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.
     
  19. Nov 17, 2011 #18

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    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: Nov 17, 2011
  20. Nov 18, 2011 #19

    I like Serena

    User Avatar
    Homework Helper

    Try your original program with:
    for(i=0;i<n-1;i+=2)
     
  21. Nov 19, 2011 #20
    Thanks for your help I like Serena!
    The program is working perfectly now. :smile:
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Array question (C++)
  1. Array C++ (Replies: 2)

  2. C - array (Replies: 2)

Loading...