0

I want to find prime numbers in a given range. The output number must be separated by a comma.

#include <iostream>
using namespace std;

int main() 
{
int i,j,lower, upper;
cin >> lower;
cin >> upper;
for (i = lower + 1; i < upper; i++)
{
    for  (j = 2; j < i; j++)
    {
        if (i % j == 0)
        {
            break;
        }
    }
        if (j == i)
        {
        cout << i ;
        cout << ",";
        }
   }
  }

Input:11 20

Output must be : 13,17,19

but my code prints an extra comma and it is not just between the numbers. Would you please help me?!

Mehrnz
  • 19
  • 1
  • 5
  • Think of the problem differently. Rather than "Put a comma after every number except the last" change it to "Put a comma before every number except the first". It is a lot easier to tell when you are at the first number than when you are at the last. – rossum Dec 20 '20 at 08:38

1 Answers1

0

Instead of printing the result right away, you can store it in a vector, so you know exactly how many numbers you want to print. Then you print your vector this way :

std::vector result;
std::string output = "";

for (size_t i = 0; i < result.size(); ++i) // Notice the ++i, not i++
{
  if (i != 0)
    output += ", ";
  output += result[i];
}

If you don't want to store your result in a vector, you can define a boolean firstResult to true if you don't have printed a coma yet, then to false when you have printed the first result, and you print the coma before the number.

int main() 
{
   bool firstResult = true;

   [...]

   if (j == i)
   {
      if (!firstResult)
         cout << ",";
      firstResult = false;
      cout << i ;
   }
}
Xobtah
  • 464
  • 7
  • 20