i'm a complete beginner to C++. its my fourth week learning it. we have this for a homework assignment:

"This program outputs all prime numbers between 3 and 100 using
a doubly-nested loop."

first off, i've done a lot of research online and from what i've seen the most efficient way is a simple program about 1/3 the size of mine using for loops. however, my teacher told us not to bother with for loops yet and hasn't taught us anything about them. so please do not reply with "oh u should be using for loops, or some other more efficient thing" lol. my problem isn't efficiency, it's functionality.

this is what i came up with so far. i thought it was all done but after running, nothing happens. maybe someone can shed some light on my errors. maybe there's a ton, maybe it's something simple? any suggestions are greatly appreciated

#include <iostream>

using namespace std;

int main()
{

int num2check = 3, innerCheck;
bool isPrime;

do
{
  isPrime = true;
  innerCheck = 2;
  
  while ((innerCheck < num2check) && (isPrime == true));
  {
    
    if (num2check % innerCheck == 0)
    {
     isPrime = false;
     break;
    }
      else 
      {
       innerCheck++;
      }
  }

  if (isPrime == true)
  {
  cout << num2check << " is prime.";
  num2check++;
  }
  else
  {
  num2check++;
  }
}while(num2check < 100);


return 0;
}

Edited 7 Years Ago by ddashtrois: n/a

i figured out what was wrong. in line 16 there was a ; after the while statement. thanks anyways.

You could make your code cleaner by using functions, assumming you have learned them already.

Not tested.

#include<iostream>
#include<cmath>
using namespace std;
bool isPrime(int i)
{  
     if(i == 2)
         return true;
   for(int j = 2; j < i; j++)  //you could optimize but this is for simplicity.
         if( i % j == 0) return false;
    return true;   
}

int main()
{
   int MAX = 100;
   int i = 2;
    while( i != MAX)
    {
           if(isPrime(i) ) cout << i  << " is Prime\n";
           i++;
    }
}
This article has been dead for over six months. Start a new discussion instead.