moister-detection-4/walk.c
2026-10-05 08:20:38 -06:00

75 lines
2.2 KiB
C

/*
* Walk the moisture log with a pointer instead of an index.
* README.md says how to build and run it.
*/
#include <stdio.h>
int sum_index(const int levels[], int count);
int sum_ptr(const int *levels, int count);
int find(const int *levels, int count, int target);
int main(void)
{
int small[3] = {4, 5, 6};
int levels[6] = {12, 3, 40, 7, 0, 100};
int one[1] = {-9};
/* The pointer walk must agree with the index walk. */
if (sum_ptr(small, 3) == sum_index(small, 3)
&& sum_ptr(levels, 6) == sum_index(levels, 6)
&& sum_ptr(one, 1) == -9) {
printf("check B1: PASS\n");
} else {
printf("check B1: FAIL, sum_ptr(levels) is %d but sum_index(levels) is %d\n",
sum_ptr(levels, 6), sum_index(levels, 6));
}
if (find(levels, 6, 40) == 2 && find(levels, 6, 100) == 5) {
printf("check B2: PASS\n");
} else {
printf("check B2: FAIL, find(levels, 6, 40) gave %d and find(levels, 6, 100) gave %d\n",
find(levels, 6, 40), find(levels, 6, 100));
}
if (find(levels, 6, 55) == -1 && find(small, 0, 4) == -1) {
printf("check B3: PASS\n");
} else {
printf("check B3: FAIL, a level that is not there should give -1\n");
}
printf("sum of levels: %d\n", sum_ptr(levels, 6));
return 0;
}
/* Given: the index walk from Moisture Detection 2, to compare against. */
int sum_index(const int levels[], int count)
{
int total = 0;
int i;
for (i = 0; i < count; i = i + 1) {
total = total + levels[i];
}
return total;
}
/*
* YOUR TASK: the same sum with no index and no [ ]. Start a pointer at levels
* and move it one element at a time while it is before levels + count.
*/
int sum_ptr(const int *levels, int count)
{
(void)levels; (void)count; /* delete once you use them */
return 0;
}
/*
* YOUR TASK: walk a pointer through levels the same way. When it points at
* target, return its index, worked out by subtracting two pointers. Return -1
* when target is not there.
*/
int find(const int *levels, int count, int target)
{
(void)levels; (void)count; (void)target; /* delete once you use them */
return -1;
}