-
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]);
}
}
-
>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?
-
Duh! That makes complete sense! Thank you.