Write a function that reverses the contents of an array of double - C Function

C examples for Function:Function Definition

Description

Write a function that reverses the contents of an array of double

Demo Code

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void reverse_array(double *arr, int arr_size);

int main(void)
{
  double test1[9];
  double test2[10];
  double test3[2];

  srand(time(NULL));/*from   w  ww .j  a v a  2s . co m*/

  for (int i = 0; i < 9; i++)
    test1[i] = rand() / (double) RAND_MAX;

  for (int i = 0; i < 10; i++)
    test2[i] = rand() / (double) RAND_MAX;

  for (int i = 0; i < 2; i++)
    test3[i] = rand() / (double) RAND_MAX;

  printf("%10s: ", "Original");
  for (int i = 0; i < 9; i++)
    printf("%5.2f ", test1[i]);
  putchar('\n');

  reverse_array(test1, 9);
  printf("%10s: ", "Reversed");
  for (int i = 0; i < 9; i++)
    printf("%5.2f ", test1[i]);
  putchar('\n');

  printf("%10s: ", "Original");
  for (int i = 0; i < 10; i++)
    printf("%5.2f ", test2[i]);
  putchar('\n');

  reverse_array(test2, 10);
  printf("%10s: ", "Reversed");
  for (int i = 0; i < 10; i++)
    printf("%5.2f ", test2[i]);
  putchar('\n');

  printf("%10s: ", "Original");
  for (int i = 0; i < 2; i++)
    printf("%5.2f ", test3[i]);
  putchar('\n');

  reverse_array(test3, 2);
  printf("%10s: ", "Reversed");
  for (int i = 0; i < 2; i++)
    printf("%5.2f ", test3[i]);
  putchar('\n');

  return 0;
}

void reverse_array(double *arr, int arr_size)
{
  double tmp;

  for (int i = 0; i < arr_size / 2; i++){
    // swap values between indexes i and (arr_size - 1 - i)
    tmp = arr[i];
    arr[i] = arr[arr_size - 1 - i];
    arr[arr_size - 1 - i] = tmp;
  }
}

Related Tutorials