-
Notifications
You must be signed in to change notification settings - Fork 124
/
exercise06.c
102 lines (78 loc) · 2.03 KB
/
exercise06.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// C Primer Plus
// Chapter 10 Exercise 6:
// Write a function that reverses the contents of an array of double and test
// it in a simple program.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void reverse_array(double *arr, int arr_size);
int main(void)
{
// test reverse_array()
printf("Testing reverse_array()\n");
double test1[9];
double test2[10];
double test3[2];
srand(time(NULL));
// initialize test array 1 with 9 random doubles
for (int i = 0; i < 9; i++)
test1[i] = rand() / (double) RAND_MAX;
// initialize test array 2 with 10 random doubles
for (int i = 0; i < 10; i++)
test2[i] = rand() / (double) RAND_MAX;
// initialize test array 1 with 2 random doubles
for (int i = 0; i < 2; i++)
test3[i] = rand() / (double) RAND_MAX;
// test array 1
printf("First Test\n");
// print original array
printf("%10s: ", "Original");
for (int i = 0; i < 9; i++)
printf("%5.2f ", test1[i]);
putchar('\n');
//print reversed array
reverse_array(test1, 9);
printf("%10s: ", "Reversed");
for (int i = 0; i < 9; i++)
printf("%5.2f ", test1[i]);
putchar('\n');
// test array 2
printf("Second Test\n");
// print original array
printf("%10s: ", "Original");
for (int i = 0; i < 10; i++)
printf("%5.2f ", test2[i]);
putchar('\n');
//print reversed array
reverse_array(test2, 10);
printf("%10s: ", "Reversed");
for (int i = 0; i < 10; i++)
printf("%5.2f ", test2[i]);
putchar('\n');
// test array 3
printf("Third Test\n");
// print original array
printf("%10s: ", "Original");
for (int i = 0; i < 2; i++)
printf("%5.2f ", test3[i]);
putchar('\n');
//print reversed array
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)
{
// reverse an array of double
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;
}
}