codescracker
c++

C++ Program to Print Prime Numbers



« Previous Program Next Program »

In this article, you will learn and get code to print prime numbers using C++ program in following ways:

Before creating these programs on printing of prime numbers, let's first understand about it.

What is a Prime Number ?

If a number can't be divisibly by any number except 1 and the number itself, then that number is called as prime number. For example, 2, 3, 5, 7, 13, 17 19 etc.

Print Prime Numbers between 1 to 100

This program prints all prime numbers between 1 to 100 using for loop. The question is, write a program in C++ to print prime numbers from 1 to 100. Here is its answer:

// C++ Print Prime Numbers between 1 to 100
// ----codescracker.com----

#include<iostream>
using namespace std;
int main()
{
    int i, chk=0, j;
    cout<<"Prime Numbers Between 1 to 100 are:\n";
    for(i=1; i<=100; i++)
    {
        for(j=2; j<i; j++)
        {
           if(i%j==0)
           {
               chk++;
               break;
           }
        }
        if(chk==0 && i!=1)
            cout<<i<<endl;
        chk = 0;
    }
    cout<<endl;
    return 0;
}

This program was build and run under Code::Blocks IDE. Here is its sample output:

C++ program print prime numbers

The dry run of above program goes like:

Print Prime Numbers in a Given Range

To print all prime numbers between a particular range (entered by user) in C++ programming, do divisibility test (as done in previous program) using for loop, from 2 to one less than that number (i.e., n-1). If the number is divided to any number from 2 to one less than that number, then the number will not be prime. Otherwise, print it as a prime number as shown here in the following program.

// C++ Print Prime Numbers in a Given Range
// ----codescracker.com----

#include<iostream>
using namespace std;
int main()
{
    int st, en, i, j, chk=0;
    cout<<"Enter the Range\n";
    cout<<"Enter the Starting Number: ";
    cin>>st;
    cout<<"Enter the Ending Number: ";
    cin>>en;
    cout<<"\nPrime Numbers between "<<st<<" and "<<en<<" are:\n";
    for(i=st; i<=en; i++)
    {
        for(j=2; j<i; j++)
        {
           if(i%j==0)
           {
               chk++;
               break;
           }
        }
        if(chk==0 && i!=1)
            cout<<i<<endl;
        chk = 0;
    }
    cout<<endl;
    return 0;
}

Here is the initial output of this program's sample run:

print prime numbers in given range c++

Now supply the two numbers as starting number and ending number say 10 and 50 to print all prime numbers between 10 and 50 as shown in the snapshot given below:

c++ print prime numbers

Same Program in Other Languages

C++ Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker