Skip to content

Instantly share code, notes, and snippets.

@makoru-hikage
Last active January 10, 2021 13:02
Show Gist options
  • Save makoru-hikage/64b3f8931f99285e9450801f1a80f4cd to your computer and use it in GitHub Desktop.
Save makoru-hikage/64b3f8931f99285e9450801f1a80f4cd to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define ARRAY_LENGTH 6
/* Assuming arrays start at zero*/
int find_opposite(int n, int count){
/* If arrays start at one, one can use (count+1) - n */
return count - n;
}
int* reverse_array (int *arr, int length){
int center = (int) (length / 2);
int temp;
for (int head = 0; head < center; head++) {
temp = arr[head];
arr[head] = arr[find_opposite(head, length)];
arr[find_opposite(head, length)] = temp;
}
return arr;
}
int main (int argc, char *argv[]){
//Initialise and define the new array
int *a = malloc(sizeof(int) * (ARRAY_LENGTH + 1));
for (int n = 0; n <= ARRAY_LENGTH; n++)
a[n] = n;
//Print the array
printf("Original Array:\n");
for (int i = 0; i <= ARRAY_LENGTH; i++)
printf("%d ", a[i]);
//Reverse and print
reverse_array(a, ARRAY_LENGTH);
printf("\nReversed Array:\n");
for (int c = 0; c <= ARRAY_LENGTH; c++)
printf("%d ", a[c]);
free(a);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment