1 Replies - 1681 Views - Last Post: 28 November 2008 - 12:40 PM Rate Topic: -----

#1 Xioshin  Icon User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 264
  • Joined: 05-November 08

Program ran until my do-while loop was implemented

Posted 28 November 2008 - 11:56 AM

Hey guys, i have this program here that solves for prime numbers using the sieve of eratosthenes. My program ran fine, and correctly, until I added the 2 lines for the do-while loop.

I want the program to run until the user types something other than 1.

#include <stdio.h>
#include <iostream>
using namespace std;
int run = 1;
int main()
{
   do {
	 int max, oneless; // I use oneless to give myself one less number than the max
					   // This is so we can go from 0-99 if max was set to 100
	 cout << "Please enter a number to check for all Prime numbers" << endl;
	 cout << "using The Sieve Of Eratosthenes: ";
	 cin >> max;
	 oneless = max-1;
	 int num[max], i, j;
	 
	 for(i=0;i<=max;i++) {
		  num[i]=i+1;
	 }
	 for(i=1;i<=oneless;i++)
	 {
		  if(num[i]!=0)
		  {
			   for(j=(i+1);j<=oneless;j++)
			   {
					if(num[j]!=0)
					{
						 if((num[j]%num[i])==0)   
						 num[j]=0;			  
						 /*check if num[j] is a multiple of num[i]*/
						 /*if it is a multiple then set it to 0*/
					}
			   }
		  }
	 }

	 for(i=1;i<=oneless;i++)
	 {
		  if(num[i]!=0) {  /* Print all numbers still flagged as Prime(=1) */
			   cout << "Prime: " << num[i] << endl;
		  }
	 }
	 cout << "Would you like to run this program again?" <<endl;
	 cout << "Type 1 for Yes, 0 for No: ";
	 cin >> run;
	 return 0;
  } while (run==1);
}



Thanks for the help.

Is This A Good Question/Topic? 0
  • +

Replies To: Program ran until my do-while loop was implemented

#2 Pwn  Icon User is offline

  • D.I.C Regular

Reputation: 19
  • View blog
  • Posts: 458
  • Joined: 25-November 07

Re: Program ran until my do-while loop was implemented

Posted 28 November 2008 - 12:40 PM

I think intead of using
do
{
     blahbitty(foo);
}while(blah foo)


it would be better to just use
while(blah foo)
{
     blahbitty(foo);
}


Since you've set your check already to =1, it's going to run once anyhow.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1