c How to remove the last comma of the output statement

Asked 2 years ago, Updated 2 years ago, 26 views

#include <iostream> 
using namespace std; 
int main(){
    int num;
    cout << "Enter you number : ";
    cin >> num;

    for(int i = 1; i <= num; i++){
        int k = i % 10;
        if (k == 3 || k == 6 || k == 9){
            cout << " *, ";
        }
        else
        cout << i << " , ";
    }
    cout << "\n";
}

I am studying c,c++ books. This code example is an example of a 3, 6, 9 game that I wrote. What I want to know is how to not print a comma after the last number is printed. Is there such a way?

c++ c

2022-09-20 19:53

1 Answers

Please refer to the code below.

#include <iostream> 

using namespace std;

int main()
{
    int num;

    cout << "Enter you number : ";
    cin >> num;

    for (int i = 1; i <= num; i++)
    {
        int k = i % 10;

        if (k == 3 || k == 6 || k == 9)
            cout << "*";
        else
            cout << i;

        if (i != num)
            cout << ", ";
    }
    cout << '\n';

    return 0;
}


2022-09-20 19:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.