1

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;
}
7
  • 2
    Question: How do you know factors[2] was ever assigned? Commented Aug 16, 2018 at 18:45
  • What are you expecting? 4? Commented Aug 16, 2018 at 18:45
  • 2
    You're incrementing j in lockstep with i, not in the if statement. Commented Aug 16, 2018 at 18:45
  • Suggest you change int factors[16]; to int factors[16] = {0}; in order to initialize the array elements to zero. Commented Aug 16, 2018 at 18:46
  • 3
    when j is 2, i is 3. 1000 % 3 != 0, so j[2] is never assigned to. Commented Aug 16, 2018 at 18:46

3 Answers 3

3

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

j is 2 the third iteration. Do you mean to say that when i == 3 and j == 2 the expression 1000 % 3 == 0 is false?
Maybe I wasn't clear, what I'm asking is, why do you say notice that j is never 2 when j == 2 the third iteration.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.