-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax_array.c
More file actions
67 lines (51 loc) · 1.37 KB
/
Copy pathmax_array.c
File metadata and controls
67 lines (51 loc) · 1.37 KB
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
#include<stdio.h>
#include<stdlib.h>
int find_max(int n, int arr[])
{
/* use 'curr_max' to keep the current max value */
int curr_max = arr[0];
for (int i = 1; i < n; ++i)
{
int a = arr[i];
if (a > curr_max) { curr_max = a; }
}
return curr_max;
}
int find_min(int n, int arr[])
{
/* use 'curr_min' to keep the current minimum value */
int curr_min = arr[0];
for (int i = 1; i < n; ++i)
{
int a = arr[i];
if (a < curr_min) { curr_min = a; }
}
return curr_min;
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Input some integers, like this:\n");
printf("%s 1 2 5 ...\n", argv[0]);
return 1;
}
int n = argc - 1; // the number of integers
/* Use malloc() allocate memory space for the array of integers.
* Each integer occupies 4 bytes, so totally we allocate 4*n bytes.
*/
int *arr = (int *) malloc(4 * n);
for (int i = 0; i < n; ++i)
{
// convert an array of 'char' into an array of 'int'
arr[i] = atoi(argv[i+1]);
}
int s = find_max(n, arr);
printf("The max value is: %d\n", s);
int x = find_min(n, arr);
printf("The min value is: %d\n", x);
// release the memory space
free(arr);
arr = NULL; // NULL is equivalent to '\0', which has ascii code is 0.
return 0;
}