Thread: Reversing elements in an array - pointers or no?

  1. #1
    Registered User
    Join Date
    May 2020
    Posts
    7

    Reversing elements in an array - pointers or no?

    DISCLAIMER: I don't want direct guidance of what to do, just to be offered some (probably cryptic) direction.

    I've been tasked with a programme to reverse the elements in an array

    Code:
    for (int i = 0; i <= height; i++)    
              {
               for (int j = 0; j <= width; j++)
              {
                //takes jth pixel into temp
                var temp = image[i][j];
                
                //puts last pixel into jth place
                image[i][j] = image[i][j-1];
                
                //puts first pixel into last place
                image[i][j-1] = temp;
            }
        }
    This chunk of code seemingly swaps the first and last elements, but obviously not the rest of them. Can someone point me in the right direction?

  2. #2
    Registered User
    Join Date
    May 2012
    Posts
    505
    To reverse an array, iterate ove half of it, swapping the element with the one at the reflection point. Don't iterate over the full array or you will undo what you just did.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reversing elements in an array
    By supermcbrownie in forum C Programming
    Replies: 5
    Last Post: 04-16-2014, 05:14 PM
  2. Reversing Words and Array of Pointers
    By Striker87 in forum C Programming
    Replies: 3
    Last Post: 03-17-2011, 11:15 PM
  3. reversing elements in array
    By dantestwin in forum C++ Programming
    Replies: 6
    Last Post: 07-08-2004, 08:24 PM
  4. reversing elements of array using a pointer
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 02-21-2002, 05:10 PM
  5. reversing elements of an array
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 02-18-2002, 09:04 PM

Tags for this Thread