0

Hi all, I have a question on how to reverse an integer array recursively with only 2 paramters.

#include <stdio.h>

void reverseAr(int ar[], int size);

int main()
{

    int size; //Array size
    int ar[100]; //The array itself
    int i; //Index to be read in the array
    int numbers; //User input digits

    printf("Enter size: ");
    scanf("%d",&size);

    printf("Enter %d numbers: ", size);

    for (i = 0; i < size; i++)
    {

        scanf("%d",&numbers);
        ar[i] = numbers;

    }

    void reverseAr(int ar[], int size)

    return 0;
}


void reverseAr(int ar[], int size)
{
    int temp;
    int start;
    int end;
    int n;
    //How could I do a reverse of array recursively?


}



/*

I have thought of the possibility:

Imagine I have an array of 4, with the input as 1 2 3 4 respectively.

Midpoint refers to half of the 'size' position.

start & end refers to the position to be swapped.

start & end is always 1 position smaller than midpoint & size respectively (Index start from 0).

1 2 3 4 -> size = 4, midpoint = 2.

            end = 3, start = 1

1 4 3 2 -> size = 3, midpoint = 1

            end = 2, start = 0

3 4 1 2 -> size = 2, midpoint = 1

            end = 1, start = 0

4 3 2 1 -> Done!!

Example 2: I have array size of 3, with input as 1 2 3

1 2 3 -> size 3, midpoint = 1

        end = 2, start = 0

3 2 1 -> Done

Example 3: I have array size of 5, with input as 1 2 3 4 5

1 2 3 4 5 -> size 5, midpoint = 2

            end = 4, start = 1

1 5 3 4 2 -> size 4, midpoint = 2

            end = 3, start = 1

1 4 3 5 2-> size 3, midpoint = 1

            end = 2, start = 0

3 4 1 5 2 -> size 2, midpoint = 1

            end = 1, start = 0

4 3 1 5 2 -> size 1, midpoint = 0

            end = 0, start = 0

I could not get what I need >.< Any help?

*/
2
Contributors
1
Reply
14
Views
2 Years
Discussion Span
Last Post by David W
0

You could use pointers to begin and end of array ...

/* recursiveReverseAry.c */  /* 2015-02-27 */

#include <stdio.h>


void reverseAry( int* beg, int* end );
void printAry( const int* ary, int size );


int main()
{
    int ary[] = { 1, 2, 3, 4, 5 };
    int size = sizeof(ary) / sizeof(int);
    printAry( ary, size );

    reverseAry( ary, ary+size-1 );
    printAry( ary, size );
    return 0;
}


void reverseAry(int* beg, int* end )
{
    if( beg >= end ) return;
    else
    {
        int tmp = *beg;
        *beg = *end;
        *end = tmp;
        reverseAry( ++beg, --end );
    }
}

void printAry( const int* ary, int size )
{
    int i = 0;
    for( ; i < size ; ++ i ) printf( "%d ", ary[i] );
    putchar('\n');
}

Edited by David W

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.