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
}

10 comments:

Unknown said...

the comment in the "if(flag==0)" is wrong , if the flag is 0 then it is a prime no.

Vibhutesh said...

Thanks for the correction .

Anonymous said...

okkkkk

Anonymous said...

Then what is the correct code?

Vibhutesh said...

The Code is corrected & updated. i.e., the above code is correct.

Anonymous said...

hey its getch(); not getche(); please correct it

Vibhutesh said...

It could be getch() or even getche(). See the function document of conio.h

Unknown said...

is it possible to run this without using flag??

Biswajit said...

when the value of i=2 then j will not be less than i, so the flag value will not get increment, and flag value will remain same. when i=3 then j will be less then i, so it will move to the if loop, but i%j==0 is false, so the flag will not increment.
So flag==0 is correct

Емилия Николова said...

for(j=2;j<=sqrt(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'
break;
}