Question #18817

Q. write a program to print all the prime numbers between 1 to 100.
Sir, i hv written a code for this but it is not working. below shown is my code
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for (i=0;i<100;i++)
{
if (i%2!=0&&i%3!=0)
{
cout<<i;
}
}
getch();
}

Expert's answer

#include "stdafx.h"

#include <conio.h>

#include <iostream>

using namespace std;

//function check if number is prime

bool IsPrime(int number)

{

if ((number & 1) == 0)

{

if (number == 2)

{

return true;

}

else

{

return false;

}

}

for (int i = 3; (i * i) <= number; i += 2)

{

if ((number % i) == 0)

{

return false;

}

}

return number != 1;

}

//main function

int main()

{

for(int i=2;i<=1000;i++){

bool prime = IsPrime(i);

if (prime){

cout<<i<<" Prime

";

}

}

cout<<"Press any key to exit...";

getch();

return 0;

}

#include <conio.h>

#include <iostream>

using namespace std;

//function check if number is prime

bool IsPrime(int number)

{

if ((number & 1) == 0)

{

if (number == 2)

{

return true;

}

else

{

return false;

}

}

for (int i = 3; (i * i) <= number; i += 2)

{

if ((number % i) == 0)

{

return false;

}

}

return number != 1;

}

//main function

int main()

{

for(int i=2;i<=1000;i++){

bool prime = IsPrime(i);

if (prime){

cout<<i<<" Prime

";

}

}

cout<<"Press any key to exit...";

getch();

return 0;

}

## Comments

## Leave a comment