Answered # problem with code

Featured Reply Banfa 597 Featured Reply Schol-R-LEA 1,003 Write a C program that should create a 10 element array of random integers (0 to 9). The program should total all of the numbers in the odd positions of the array and compare them with the total of the numbers in the even positions of the array and indicate ...

1

Line 8 initialising b to 0 means that at line 9 you get a divide by zero error while trying to get the remainder after dividing a by b.

1

The problem is that, just as with division, taking the modulo of a number by zero is undefined; what you are actually getting is a division by zero exception, as internally, both division and modulo (or rather, strictly speaking, remainder) are calculated using the same assembly instruction. Thus, this is one place where you actually want to initialize `b`

to one instead of zero. No, on second thought, start at 2 - there's no point in starting at 1, as every number is divisible by that, and it would give you a false negative for everything.

I might also suggest that you only iterate `b`

from 1 to `ciel(sqrt(a))`

, as you know that no prime divisor of a number is going to be more than that number's square root.

```
for(b = 2; b <= (int) ciel(sqrt(a)); b++){
```

Finally, you might want to actually print the results when you find a prime number other than 2. Just sayin'.

Anyway, here is a simplified version of your code, though it assumes that the C99 `<stdbool.h>`

library is available (it should be, with any compiler newer than, say, 2004). It isn't actually tested, but it should fix most of the problems in the original.

```
#include <stdio.h>
#include <stdbool.h>
int main() {
int a, b, c;
bool composite;
printf("2, ");
for(a = 3; a <= 100; a += 2) {
composite = false;
for(b = 2; b <= (int) ciel(sqrt(a)); b++) {
c = a % b;
if (c == 0) {
composite = true;
break;
}
}
if (!composite) {
printf("%d, ", a);
}
}
return 0;
}
```

*Edited 3 Years Ago by Schol-R-LEA*

This question has already been answered. Start a new discussion instead.

Recommended Articles

Hi. so this is actually a continuation from another question of mineHere but i was advised to start a new thread as the original question was already answered.

This is the result of previous question answered :

code for the listbox - datagridview interaction

At the top of the code ...

the function that I created to find the ...