Print Prime Numbers in C++

This little program shows how to take input an integer specifying the number for consecutive prime numbers to print. All numbers starting from 1 are continuously checked for being prime. If found to be prime, they are immediately printed. If not, the current number is simply skipped and the loop variable is incremented to get a new number i.e. 1 greater than the current number. 
The logic for checking the prime property is simple enough. The original number is taken into account. Now a range starting from 2 to one less than the number is taken. Say, if the original number is 10, then the range will be from 2 to 9 i.e. 2,3,4,5,6,7,8,9 will be the numbers checked in the for loop. All numbers in between this range are checked for if they are divisible by the original number i.e. by 10. If they are divisible i.e. they have a remainder of Zero when divided by the original number itself, means that the original number is not prime. This is because there exists a number which divides the original number itself and goes against the definition of a prime number. See the code below followed by the source code download:


#include <iostream>

using namespace std;

int main()
{
    int n, i = 3, count, c;

    cout<< "Number of Prime Numbers Required: \n" ;
    cin>> n ;

    if ( n >= 1 )
    {
        cout<< "First " << n << " Prime Numbers are : \n" ;
        cout<< "2\n";
    }

    for ( count = 2 ; count <= n ;  )
    {
        for ( c = 2 ; c <= i - 1 ; c++ )
        {
            if ( i%c == 0 )
            break;
        }
        if ( c == i )
        {
            cout<< i << "\n" ;
            count++;
        }
        i++;
    }

    return 0;
}

Download Source Code Here. Notice that the C++ Souce Code is written in Code::Blocks 12.11 IDE available for direct download Here.

Please ask your questions and list your suggestions below in the comments section.

No comments:

Post a Comment

Custom Search