Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Making a recursive function to reverse all the elements of an array.

$
0
0
void reverseArray(double A[], int len, int i)

precondition: A is an array of length len and 0 <= i < len

postcondition: The entries in the subarray from index i to index len - 1 -i have been reversed


So here is my code:

#include <stdio.h>


void arraySwap(double B[], int k, int j);
void reverseArray(double A[], int len, int i);


int main()
{
    double array1[7] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
    int length = 7;
    int m = 0;

    reverseArray(array1, 7, 0);

    for (m; m < 7; m++)
    {
        printf("%f, ", array1[m]);
    }



}

void arraySwap(double B[], int k, int j)
{
    int temp;
    temp = B[k];
    B[k] = B[j];
    B[j] = temp;

}


void reverseArray(double A[],int len, int i)
/*Precondition: A is an array of length len and 0 <= i < len
 Postcondition: The entries in the subarray from index i to index len-1-i have been reversed
 You may use the above arraySwap function and your function MUST BE RECURSIVE */
{
    int low = i;
    int high = len - 1 - i;


    if (high - low > 0)
    {
        arraySwap(A, low, high);
        reverseArray(A, low+1, high-1);
    }


}



Its only reversing the first and last elements of the array and I'm not sure while its not really recursive.

Viewing all articles
Browse latest Browse all 51036

Trending Articles