arrayscprimes

how to create an array that stores prime numbers?

Given an array of 8 integers by the user, the program should print out every prime number entered. The program after entering some number stops, I don't know why. Could you tell what I did wrong please? code:

``````#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int main()
{
const int N=8;
int i, j, count, x;
int arr[N];
int prime[N];
j = 2;
for(i = 0; i < N; i++)
{
printf("Enter a number %d:", i + 1);
scanf("%d", &arr[i]);
if (arr[i] == 1)
{
prime[i] = arr[i];
count++;
}
else
{
do
{
x=arr[i] % j;
if (x != 0)
j++;
else
break;
}
while(true);
if(arr[i] == j)
{
prime[i] = arr[i];
count++;
}
}
}

for (i = 0; i < count; i++)
printf("%dth prime number:%d\n", i + 1, prime[i]);

getch();

return 0;
}
``````

Solution

• If the user enters an integer which is less than the previous one, your program ends up in an infinite loop. You probably meant to initialize j in the else clause, just before the do-while loop.

Also note that you should check the return value from scanf to make sure that an integer was actually entered.