Question

I am confused searching for all prime numbers between 1 and 1000. I am trying to do this and print them 13 per line. My code works for the first 5 numbers and then just ends. Here is what I have so far and my current output is 12357. Any ideas of what's wrong? Thanks in advance!

void removenonprimes(int d, int ary[]) {
  int i;
  int h = 0;

  for (i = 0; i < sizeof(ary); i++) {
    h = ary[i];
    if (h % d == 0 || h == d) {
      ary[i] = 0;
    }
  }
}

void prnt(int ary[]) {
  int i;
  int holder;
  int count = 0;

  for (i = 0; i < sizeof(ary); i++) {

    if (i > 1) {
      removenonprimes(i, ary);

      holder = ary[i];

      //case for when number is not 13th in its line
      if (holder != 0 && count != 13) {
        printf("%d", holder);
        count++;
      }
      //case for when number is 13th in its line
      else if (holder != 0 && count == 13) {
        printf("%d\n", holder);
        count = 0;
      }
    } else {
      printf("  %d", ary[i]);
    }
  }
}
Était-ce utile?

La solution

You can't check against sizeof(ary) because sizeof(ary) returns the size of the array pointer, not the size of the array. You need to pass the size (1000) through as a parameter to your functions, or use a global constant.

void prnt(int ary[], arySize){

...

for(i = 0; i < ary; i++){

and call it like

prnt(nums, 1000);

You need to do a similar thing for your removenonprimes function.

Autres conseils

  1. In your for loop you use, "i < sizeof(data);" and I do not see data declared.
  2. divisor is declare where?

I believe point number 1 will fix your issue though, you should be looking at the length of the array.

To determine the number of elements in the array :

int n = sizeof(ary) / sizeof(int);

for(i = 0; i < n; i++)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top