# Thread: Issue storing Prime numbers in an array and then prinitng

1. ## Issue storing Prime numbers in an array and then prinitng

Hi I am trying to write a program that generates the prime numbers under a 1000. The program itself works fine until i edit it and try to store the values in an array and then print that array. I know im pretty close to fixing this but i cant seem to find where im going wrong. Any help would be great

Code:
```#include <stdio.h>
int main ()
{
int array[1000];

int j=0;

int i = 0;		/*assigns value to i*/

printf("The following numbers are prime:\n\n");

while (i < 1000){

int	num = 2;

int non = 0;

while ( num < i ){

if ( i%num == 0) { /*true statement means number is not prime */
/*adds 1 to value of i in each time*/
non++;
}

num++;
}

if (non ==0){

scanf("%d",&array[i]);/*prints the prime number for the user */
}
i++;/*adds 1 to value of count*/
}
i=0;

while (i<=1000){

printf("%d",array[i]);

i++;

}

return 0;	/*Terminates program*/
}```

2. Your scanf line is waiting for user input. Its not adding elements to the array, which I think is what you were wanting. But just fixing that isn't going to solve all your problems. I think you have faulty logic in your algorithm.

3. you are not at all storing prime numbers into array.

4. I understand that im not scanning in the prime numbers and like you said its a week program overall i know that but i would prefer if i could fix it then make it sparkle lets say!

5. Once you know a number is prime, you need to put it into your array and increase the index for the next number...
Code:
`array[index++] = prime_number;`
If you use more meaningful variable names the function of your code would be more apparent to you.

Also... there are considerable optimizations you can do here... First of all we all know that 1, and 2 are prime numbers so you can start your search at 3. Second all prime numbers are odd numbers (even numbers are divisible by 2) so you can increment your counter by 2 instead of 1.

6. @commontater thanks for your advice i see how it would make it much neater and have found similar code on these forums and have changed my variable names etc to that code as i deemed it to be better. however when i compile the program it prints out random numbers but it is printing from the array which is progress!thanks again

7. Are you in the same class as Interista?

8. Originally Posted by CommonTater
First of all we all know that 1, and 2 are prime numbers so you can start your search at 3.
FYI: Most people consider 2 to be the first prime.

Prime number - Wikipedia, the free encyclopedia
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
The first 1000 prime numbers http://primes.utm.edu/lists/small/1000.txt

Tim S.

Popular pages Recent additions