Reversing elements in an array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dru
    New Member
    • Sep 2006
    • 29

    Reversing elements in an array

    Problem:
    Reversing the elements of an array involves swapping the corresponding elements of the array: the first with the last, the second with the next to the last, and so on, all the way to the middle of the array.

    Given an array a , an int variable n containing the number of elements in a , and two other int variables, k and temp , write a loop that reverses the elements of the array.

    Do not use any other variables besides a , n , k , and temp .

    Anyone know how to do this?
  • sicarie
    Recognized Expert Specialist
    • Nov 2006
    • 4677

    #2
    I would just store the value in a variable, then move the value to be switched in, then copy the temp value into the place you just moved it, for however big the array is.

    What do you have for your algorithm?

    Comment

    • dru
      New Member
      • Sep 2006
      • 29

      #3
      no algorithim just have to figure out that what to put

      Comment

      • sicarie
        Recognized Expert Specialist
        • Nov 2006
        • 4677

        #4
        Originally posted by dru
        no algorithim just have to figure out that what to put
        The thing to do when you are programming is to create an algorithm - a method of how you are going to program. If you follow good programming techniques, you can be quite literally 100x faster than a programmer who doesn't.

        I would start by making a very general statement of what you need to do:

        Manipulate an array

        And go through that and just break it down into smaller and smaller bits until it becomes almost code (what is called pseudocode), and you will be able to code it very easily. So from above, I would say

        declare an array
        reverse the elements in an array

        And then do it again:

        declare an array
        declare a temporary value
        for each item in the array
        store it in a temporary value
        move another value into that spot
        move the temporary value into the other spot

        Do you see how it is turning into code? (the declares, and the 'for' - though it's not quite there yet) After you do that one or two more times, you will have what looks like code sitting in front of you, and you'll be able to quickly and efficiently write your program.

        Comment

        Working...