How can I remove the last comma from a loop in C++ in a simple way?

后端 未结 6 1328
梦毁少年i
梦毁少年i 2020-12-06 13:31

This program is for printing prime numbers till the input given and separating every prime number with a comma.

void main(){

    int N, counter=0, isPrime;
         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 13:57

    The easiest way is to output the first or last value manually:

    #include 
    #include 
    
    using namespace std;
    
    int main() {
        int N, counter = 0;
        bool isPrime;
    
        cout << "Enter maximum range: ";
        cin >> N;
        if (N>=2) {
            cout << "2";
        }
        for (int j = 3; j <= N; ++j) {
            isPrime = true;
            for (int k = 2; k < sqrt(j)+1; ++k) {
                if (j % k == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                cout << ", " << j;
                counter++;
            }
        }
        cout << endl;
        system("pause");
    }
    

提交回复
热议问题