Ok, so I am trying to implement the Collatz problem in C, and record/print the time it takes for the while loop to execute. I am supposed to report both the number of “ticks” and the time in seconds. However, I am getting some seemingly simple errors from my code but for whatever reason, I am not sure how to correct them.
This is my code
#include <stdio.h>
#include <time.h>
void main() {
int n, c = 0;
printf("Please enter an integer...\n");
scanf("%d", &n);
clock_t start; /* Line 8 */
clock_t finish; /* Line 9 */
start = clock();
while (n != 1) {
if (n%2 == 0)
n = n/2;
else
n = (3*n)+1;
c++;
printf("n=%d\n", n);
}
finish = clock() - start;
double interval = finish / (double)CLOCKS_PER_SEC;
printf("%d iterations\n", c);
printf("%f clock cycles", finish);
printf("%f seconds elapsed", interval);
}
These are the errors Visual Studio is reporting
Line 8 and 9 Errors
‘clock_t’ : illegal use of this type as an expression
syntax error : missing ‘;’ before identifier ‘start’
‘start’ : undeclared identifier
I am also getting an ‘undeclared identifier’ error for all lines in which ‘start’ or ‘finish’ show up
Try moving the variables to the top before any statements…
The rest of your errors are just consequences of these not being declared properly.
In a later C standard (C99) declarations can be mixed in anywhere. Often it’s just easier to make it compliant… Another approach is to introduce a block { } like so:
In this case, it’s not an ideal solution as it’s simple enough to rearrange your code. But sometimes this is useful when trying to make C99 code compile in C89 without rearranging things too much.