Jump to content

Simple C coding question?


Recommended Posts

I am trying to write a program that stores all the prime numbers up to 1000 in an array.. I can do that.. but when it's doing the check to see if it's prime, if it isn't, it just sets it to 0. So when I try to print out all my prime numbers, it prints all the 0s out with it. How do I remove the 0s from the array? Or what's a better way to do this..


#include "stdafx.h"


#define size 1000

int main()
{

int arr[size], i, j=1, remainder, primecount=0, max=size;


   for(i = 0;i < size; ++i)
   {
     arr[i] = j++;
   }

   for(j = 2; j <= size; j++){

       for(i = j; i < size; i++){
         remainder = arr[i] % j;

if(remainder == 0)
arr[i] = 0;

       }
   }





for(i=0;i<size;i++){
if (arr[i]!=0)
primecount++;

}

   for(i = 0; i < size; i++)
   {
printf("\n %d ",arr[i]);
   }
printf("There are %d prime numbers up to %d.\n",primecount,max);
return 0;  
}

Link to comment
Share on other sites

  • 2 weeks later...

If for some reason you are still working on this 11 days later... Why remove them? You could just add a single if statement and only print it if the value in the array isn't 0. At least this is the easiest way. You can't simply "remove" them from the array, you would have to make a new array the size of the number of primes you have and copy the primes over.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Who's Online   1 Member, 0 Anonymous, 2092 Guests (See full list)

×
×
  • Create New...