Lesson 9。
This commit is contained in:
40
09/Exercise01.c
Normal file
40
09/Exercise01.c
Normal file
@@ -0,0 +1,40 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int findMaxFirst(int sheep[]) {
|
||||
int max = 0;
|
||||
int i = 0;
|
||||
max = sheep[0];
|
||||
for (i = 1; i < 100; i++) {
|
||||
if (sheep[i] > max) {
|
||||
max = sheep[i];
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
int findMaxRecursive(int sheep[], int start, int prevMax) {
|
||||
if (start == 100) {
|
||||
return prevMax;
|
||||
}
|
||||
else {
|
||||
return findMaxRecursive(sheep, start+1, sheep[start] > prevMax? sheep[start]:prevMax);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int sheep[100] = {0};
|
||||
int i = 0;
|
||||
int max1 = 0, max2 = 0;
|
||||
for (i = 0; i < 100; i++) {
|
||||
sheep[i] = rand() % 1000;
|
||||
}
|
||||
// for (i = 0; i < 100; i++) {
|
||||
// printf("%d\n", sheep[i]);
|
||||
// }
|
||||
max1 = findMaxFirst(sheep);
|
||||
max2 = findMaxRecursive(sheep, 0, 0);
|
||||
printf("By first method, the max is %d\n", max1);
|
||||
printf("By second method, the max is %d", max2);
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user