FrancisDoy
FrancisDoy

Reputation: 79

Reverse order through pointer

I can't seem to solve this exercise my professor gave me. So I'm suppose to use pointers in this exercise to reverse the order of the original array.

Here is what I made so far.

#include <stdio.h>
#define SIZE 10

void reverse(int *a, int size);

int main(void){
    int array[SIZE]={1,2,3,4,5,6,7,8,9,10};
    int i;

    printf("The original order is:\n");

    for (i=0; i<SIZE; i++){
        printf("%5d", array[i]);
    }

    reverse(array, SIZE);

    printf("\nThe reverse order is:\n");

    for (i=0; i<SIZE; i++){
        printf("%5d", array[i]);
    }

    return 0;
}

void reverse(int *a, int size){
    int j;
    int hold;

    for(j=0; j<size-1; j++){
        hold = a[j];
        a[j] = a[size-1-j];
        a[size-1-j] = hold;
    }
}

Upvotes: 0

Views: 69

Answers (2)

justmscs
justmscs

Reputation: 756

In the reverse function, you did swap the value, but you swap them back again!

Try this:

void reverse(int *a, int size){
    int j;
    int hold;

    for(j=0; j<size/2; j++){
        hold = a[j];
        a[j] = a[size-1-j];
        a[size-1-j] = hold;
    }
}

Upvotes: 1

Aki Suihkonen
Aki Suihkonen

Reputation: 20027

Running the algorithm from 0..N will swap first element 0 with N, and then the element N back with element 0. To fix it, use

for (j=0; j<size/2; j++)

Upvotes: 0

Related Questions