## Trending News

# How to print all prime numbers from 1 to 10000 in c++?

This is what i have done:

#include<iostream>

using namespace std;

int Prime(int);

int main()

{

int number;

cout<<"Prime numbers from 1 to 10000 are: "<<Prime(number);

system("pause");

return 0;

}

int Prime(int number)

{

for(number=2; number<=10000; number++)

{

for(int i=2;i<number/2; i++)

{

if (number%i!=0)

return number;

}}}

### 1 Answer

- JeroonkLv 69 years agoFavorite Answer
1. A problem is the "return number;" statement in "Prime". This will not only abort the inner loop which checks if it is prime, it will also abort the outer loop, it just exits the "Prime" function altogether.

This wouldn't be a problem if you move the 1 to 10000 loop (the outer one) to the "main" function. From there you call "Prime" each time to check if a number is prime:

2. The second problem is the inner loop in "Prime". You are trying to check if the number is divisible by any value "i" from 2 to "number / 2", which would mean it is prime.

However, since you placed your return inside the loop.. this means that for the first value of "i" where "number % i != 0", it will abort saying that it's prime. That is not correct. It should only say if it is prime when it has completed the loop for all values of "i".

Fixed code: