Reputation: 1414
When I run this code, the printf()
function seems to give a random large number, as if it is calling an array that is out of bounds. What is going on here?
#include <stdio.h>
#include <math.h>
int main(void)
{
int test_num = 1000;
int factors[16];
for(int i = 1, j = 0; i < test_num; i++, j++) {
if(test_num % i == 0)
factors[j] = i;
}
printf("%d", factors[2]);
return 0;
}
Upvotes: 1
Views: 139
Reputation: 1178
When j == 2
, i == 3
and 1000 % 3
does not equal 0. It equals 1. Not passing your if
statement condition. Therefore factors[2]
will be undefined (since you didn't initialize your array). Hence the large number.
Upvotes: 0
Reputation: 114508
Most likely, the problem is that you are incrementing j
even when you don't assign i
.
The sequence of factors you get is 1, 2, 4, 5, 8, 10, ... You probably want to assign those to the indices 0-5 (inclusive), not 0, 1, 3, 4, 7, 9, etc.
Change your loop as follows:
for(int i = 1, j = 0; i < test_num && j < 16; i++) {
if(test_num % i == 0) {
factors[j] = i;
j++;
}
}
The main point is only to increment j
when i
fits your criterion. You also want to make sure that you don't go out of bounds (&& j < 16
).
Upvotes: 3
Reputation: 27812
If you print out i
and j
in the loop, notice that j
is never 2.
Thus, factors[2]
is never initialized, so you will print out junk.
Upvotes: 0