Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   finding prime using bool (http://www.programmingforums.org/showthread.php?t=15185)

gmann145 Feb 14th, 2008 12:01 PM

finding prime using bool
 
Hey I'm trying to figure out how to fix this program, i need to create and write a file Prime.txt and store prime numbers 1-100 using bool. right now I'm stuck and not sure whats wrong. All I'm getting is the black screen, and I'm not sure exactly where the file is then stored


:

  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4.  
  5. bool isPrime(int numcheck);
  6. void write_prime(int prime, ofstream &outfile);
  7.  
  8. int main()
  9. {
  10.         ofstream primefile("prime.txt");
  11.  
  12.         for (int ntc = 2; ntc = 100; ntc++)
  13.         {
  14.                 if(isPrime(ntc))
  15.                         write_prime(ntc, primefile);
  16.         }
  17.         primefile.close();
  18.         return 0;
  19. }
  20.  
  21. bool isPrime(int numcheck)
  22. {
  23.         for (int x = 2; x < numcheck; x++)
  24.         {       
  25.                 if(numcheck % x == 0)
  26.                 {
  27.                         return false;
  28.                         break;
  29.                 }
  30.  
  31.         }
  32.         return true;
  33. }
  34.  
  35. void write_prime(int prime, ofstream &primefile)
  36. {
  37.         primefile << prime << "\n";
  38.  
  39. }


Ancient Dragon Feb 14th, 2008 2:38 PM

Re: finding prime using bool
 
line 12: replace ntc = 100 with ntc < 100

titaniumdecoy Feb 14th, 2008 2:39 PM

Re: finding prime using bool
 
I believe that the file will be written to the directory in which the executable resides. If you are using an IDE which takes care of compilation for you, you may have to dig around to find it.

Ancient Dragon Feb 14th, 2008 2:43 PM

Re: finding prime using bool
 
The problem was not the file but that infinite loop on line 12. The program never was able to write anything to the file.

titaniumdecoy Feb 14th, 2008 3:26 PM

Re: finding prime using bool
 
My bad. I have had a problem in the past with not being able to locate the output of C++ programs that I wrote.

Sane Feb 14th, 2008 6:19 PM

Re: finding prime using bool
 
Just as an aside, if you're generating a list of primes (as opposed to determining whether or not an arbitrary number is prime), the Sieve of Eratosthenes is a fairly intuitive and simple algorithm for doing just that. It's easy to implement, and might be a fun programming excercise for you. It's by no means necessary for the requirements of the program, but it will surely impress your teacher (if this is an assignment).


All times are GMT -5. The time now is 3:52 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC