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.

//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:

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

Thanks for the correction .

okkkkk

Then what is the correct code?

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

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

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

is it possible to run this without using flag??

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 correctfor(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;

}

Post a Comment