1

I have this piece of code which should output all prime numbers to n(where n is the user input) separated by commas.

#include <iostream>
using namespace std;
void check(int a, int ra)
{
    int count = 0;
    for(int i = 1;i<=a;i++)
    {
        if(a%i==0)
            count++;
    }
    if(count<3)
    {
        cout << a;
        cout << ", ";
}
}
int main(int argc, const char * argv[]) {
    int a;
    cin >> a;
    for(int i = 2;i<=a;i++)
        check(i,a);
    return 0;
}

Currently, it does everything alright except output looks like this (assume input is 10): 2, 3, 5, 7, I need to get rid of comma after 7 and nothing I could think of worked.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • This is actually a fairly common issue and has been covered in other issues on this page, e.g. https://stackoverflow.com/questions/2125849/how-can-i-recognize-the-last-iteration-in-a-c-while-loop Basically, you can special-case either the first or last iteration. Doing it for the first iteration makes for potentially slightly faster code. – Joris Timmermans Nov 14 '22 at 14:35
  • Another nice discussion on the same problem elsewhere on stack exchange: https://codereview.stackexchange.com/questions/207035/elegantly-exclude-part-of-an-operation-for-the-last-iteration-in-a-loop – Joris Timmermans Nov 14 '22 at 14:36

0 Answers0