If that is your actual code you have 4 bugs:
- 2 line comment scopes out a line of your code
- the second if should check
count < n
not count <= n
as if count == n
you cannot write to arr[count]
- You cannot print
arr[count]
only arr[count-1]
which is probably what you mean
- In the case where n is less than 4 you still set
arr[1]
, arr[2]
and arr[3]
which may be out of bounds
It is of course also inefficient to call sqrt(x)
in every loop iteration, potentially you should call it outside and there may be a potential rounding issue bug due to the way square roots are calculated, so you might prefer:
while( arr[j] * arr[j] < x )
It would be preferable not to make this global and to pass it into your function.
It would also be preferable to move the main loop logic of your program outside of main()
.
I'm surprised you say you program works for n=1, 2 and 3 as it looks like you are setting out of bounds.