Thread: Switching Array Elements

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    2

    Switching Array Elements

    Ok guys I'm a newb so go easy on me. I am trying to reverse the corresponding elements in the array I created. I don't understand why this isn't working.

    Code:
    #include <stdio.h>
    int main ()
    {
    
    const int n=6;
    int k;
    int temp;
    int a[n];
    
    for (k=0; k<n; k++) {
        a[k]=0;
        a[k]=k+1;
    }
    printf("Before\n");
    for (k=0; k<n; k++) {
        printf("%d\n" , a[k]);
    }
    for (k=0; k<n; k++) {
        temp=a[k];
        a[k]=a[n-(k+1)];
        a[n-(k+1)]=temp;
    }
    printf("After\n");
    for (k=0; k<n; k++) {
        printf("%d\n" , a[k]);
    }
    
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I don't understand why this isn't working.
    Code:
    for (k=0; k<n; k++) {
        temp=a[k];
        a[k]=a[n-(k+1)];
        a[n-(k+1)]=temp;
    }
    This loop has two parts. The first part completely reverses the array from the beginning to the middle. The second part completely reverses the array from the middle to the end. What happens when you reverse an array twice?
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Nov 2006
    Posts
    2
    Duh! That makes complete sense! Thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  3. way to check 3 elements of array and set 4th
    By Syneris in forum C++ Programming
    Replies: 3
    Last Post: 01-09-2006, 11:30 AM
  4. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  5. A simple question about selecting elements in an array
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 08-30-2001, 10:37 PM