Showing posts with label prime numbers. Show all posts
Showing posts with label prime numbers. Show all posts

C++ Program/code to print all prime numbers between 1 to n.

10 comments
0//In this program the user will be prompted to enter a number 'n' (integer), and the program will
//print all the prime number between 1 to n.

#include<iostream>              //For Input/Output Stream Function
#include<conio.h>                //For Console Input/Output function like clrscr & getche
using namespace std;           //Using the "standard" namespace of iostream class
void main()
{
clrscr();                                //For Clearing the console screen
int i,j,n,flag;
cout<<"Enter max. limit:";
cin>>n;                                //User enters the value of 'n'
for(i=2;i<=n;i++)                //Counting starts from '2' as '1' is not a prime number
{
flag=0;                                 //Initializing the Flag variable inside the first for loop, in order to check  for(j=2;j<i;j++)                  //for prime number 
{
if(i%j==0)                          //Checking for the condition that if, 'i' is fully divided by 'j'
flag++;                                //If 'i' is fully divided by 'j' then increment the value of 'flag'
}
if(flag==0)                          //Checking for the condition in which the value of flag is still zero
cout<<i<<"\t";                  //If Flag=0, then its a prime number, therefore print its value
}
getche();                             //To exit the program after an user's keystroke
}

Read More...