### prime numbers from array

hi i am still a beginner in c++ and still didn't learn functions and not allowed to use libraries . so a friend of mine challenged me to write a program that shows only prim numbers from an array what my program do when entering numbers from 1 to 10 it shows the 1,5,7,9,10 showing 1o and doesn't show the 3 can any body help.

 ``123456789101112131415161718192021222324252627282930`` `````` #include using namespace std; void main() { int NUM[10]; int r=0; int count=0; for (int i = 0; i < 10; i++) { cin>>NUM[i]; } for (int k = 0; k < 10; k++) { count=0; for (int i = 2; i <= NUM[i]; i++) { if (NUM[k] % i==1) { ++count; } if (count==2) { cout<<"this number is prime : "<
Last edited on
Your inner loop is odd -- hard to figure out.

Why do you store the input into array? Why not read one value, check if it is prime, and if yes, then append it to list? In tge end just show the list.
the inner loop tries every possible divisor so if the value in the array is divisible by i count will increase. in the second if, the prime should enter the if above 2 times ( divisible by 1 and its-self).
Last edited on
I have tried what you said but the same values just still appear like no 3 , it shows 10 16 22...
 ``123456789101112131415161718192021222324252627282930313233343536`` ``````#include int main(void) { int NUM[10]; // define a 10-element array of type int bool isprime; // define a bool to check if a number is prime or not std::cout<<"This program gets 10 numbers and prints out the ones that are prime."<>NUM[counter]; // get the number std::cin.ignore(); // get the carriage return } for(int outer=0;outer<10;outer++) // we need this outer loop to loop through the 10 elements in the array { isprime=true; // set isprime to true for(int inner=2;inner
Last edited on
% is modulo. `a % b == 0`, when `a == k*b`.
For example, `4 % 3 == 1`.

@usanfriends you need to add one condition in the last if, because we can't print that 1 is prime. or change the code in another way
 ``` This program gets 10 numbers and prints out the ones that are prime. Element #1: 1 Element #2: 2 Element #3: 3 Element #4: 4 Element #5: 5 Element #6: 6 Element #7: 7 Element #8: 8 Element #9: 9 Element #10: 10 Element #1: 1 is prime. Element #2: 2 is prime. Element #3: 3 is prime. Element #5: 5 is prime. Element #7: 7 is prime. ```

I did this..
 ``1234`` `````` if(isprime&&NUM[outer]!=1) // if the number is prime and isn't 1 print it out { std::cout<<"Element #"<

 ``` Element #1: 1 Element #2: 2 Element #3: 3 Element #4: 4 Element #5: 5 Element #6: 6 Element #7: 7 Element #8: 8 Element #9: 9 Element #10: 10 Element #2: 2 is prime. Element #3: 3 is prime. Element #5: 5 is prime. Element #7: 7 is prime. ```
eyenrique wrote:
@usanfriends you need to add one condition in the last if, because we can't print that 1 is prime. or change the code in another way

Yes, quick fix. :)
Topic archived. No new replies allowed.