Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How can I remove last comma form the loop

0 votes
asked Oct 15, 2022 by Ardean Josh Largado (120 points)
int main()
{
    int  num[10];
    
    cout << "Enter 10  numbers\n";
    
    for (int i=0; i < 10; i++) {
        cin >> num[i];
        
    }
    cout << "The even numbers are:";
    for (int i=0; i < 10; i++){
        if( num [i]%2==0){
            cout << num[i] << ",";
        }
        
      
    }
        cout << endl;
        
        cout << "The odd numbers are:";
    for (int i = 0; i < 10; i++){
        if(num[i]%2==1){
            cout << num[i] << ",";
        }
    }
}

I want my output is like this: 2, 4, 6, 7, 8
but the output my program print is: 2, 4, 6, 8,
it has last comma how can I remove it?

1 Answer

+1 vote
answered Oct 20, 2022 by Peter Minarik (86,180 points)

You either use just space to separate and put a space before every item. Or, you print a comma before every item, but you only do it after the first (0th) item:

#include <iostream>

int main()
{
    const int count = 5;
    int numbers[count] = { 1, 2, 3, 4, 5 };

    // List just with space separator
    std::cout << "The numebers are:";
    for (int i = 0; i < count; i++)
        std::cout << " " << numbers[i];
    std::cout << std::endl;

    // List with come separator
    std::cout << "The numebers are: ";
    for (int i = 0; i < count; i++)
    {
        if (i > 0)
            std::cout << ", ";
        std::cout << numbers[i];
    }
    std::cout << std::endl;

    return 0;
}

I hope this helps. :)

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...