-
problem running code
First of all, here is the code:
Code:
//primenumber.cpp
//exercise 2, chapter 3, feb 19, 2008
//Prints out prime numbers with nested for loops
#include <iostream>
using namespace std;
int main()
{
cout << "All prime numbers between 0 and 200.\n\n";
bool primeNumber = false;
for (int i = 0; i < 200; i++)
{
for (int j = 0; j < i; j++)
{
if ( ( i % j ) == 0 )
{
cout << i << " is not a prime a number.";
primeNumber = true;
break;
}
if (!primeNumber)
{
cout << i << " is a prime number." << endl;
}
}
}
cout << "\nThere they are!\n" << endl;
return 0;
}
When I run the program, no text goes on the screen. (Okay, sometimes the prime numbers between 0 and 200 does) But, I just get a screen saying "primenumbers.exe has encountered an error and needs to close." One of those Windows errors. This was under windows XP. Compiled with MinGW C++ compiler under Code::Blocks IDE.
-
the modulo operator (%) accepts two (almost always) integers, ex a % b, with the divisor (b) being non-zero. you loop over two variables, your dividend (i) going from 0-199, and your divisor (j) going from 0-i. try '0 % 1' on your calculator--does it work? now try '1 % 0'.
modulo is the remainder after division. whats the remainder of 1/0 ? hopefully you see your error.
-
If you take a close look you will see that on the second iteration you are performing 1 % 0, which triggers an unhandled exception because of a devision by 0 attempt.
You fix it by changing your for loops to cope with j not ever being 0.
Code:
for (int i = 1; i <= 200; i++)
{
for (int j = 1; j <= i; j++)
You will realize then your code contains another bug. Everything is not a prime number. But you'll can work that one out
-
also, 0 is not a prime number, so you can save another iteration.
-
Working on that other bug now. Trying to fix it. O_O