954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Prime numbers in C++

Hi techies,
I am new into C++. I like to write a program that generates all the primes number between 1 and 100. Below is the code I have written but brings no output.
Thanks for any help...

//A program that generates all of the prime numbers between 1 and 100

#include <iostream>

using namespace std;

int main()
{
    int n;

    for(n=1; n>=100; n++)
    {
        bool isPrime = true;

        for(int i=2; i<n; i++)
        {
            if (n%i==0)
            {
                isPrime = false;
                break;
            }
        }
        if(isPrime)
        {
            cout<<n <<" is Prime";
        }
    }

    return 0;
}
easyb
Newbie Poster
8 posts since Oct 2009
Reputation Points: 10
Solved Threads: 1
 

Your problem is that this for loop never runs. You have the greater than/less than sign mixed up.
change

for(n=1; n>=100; n++)

to

for(n=1; n<=100; n++)
MyrtleTurtle
Junior Poster
101 posts since Feb 2010
Reputation Points: 63
Solved Threads: 11
 

As the first replier said, you've got the inequality signs all wrong. Change your code to this:

#include <iostream>

using namespace std;

int main()
{
    int n;

    for(n=1; n<101; n++)//or n<=100
    {
        bool isPrime = true;

        for(int i=2; i<n; i++)
        {
            if (n%i==0)
            {
                isPrime = false;
                break;
            }
        }
        if(isPrime)
        {
            cout<<n <<" is Prime";
        }
    }

    return 0;
}
tkud
Posting Whiz in Training
235 posts since Sep 2009
Reputation Points: 13
Solved Threads: 46
 

Thank you for helping me out. It works...

easyb
Newbie Poster
8 posts since Oct 2009
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: