0

I have this program that prints all the prime digits that are present in a number in the order of their apparition from right to left. That part was simple enough.

The book wants that at the end the program to output the numbers in the console like this:"2 and 3 and 7" for example. I don't know how to implement that.

using namespace std;

int main()
{
    int n,digit;
    cin>>n;
    while (n>0)
    {
        digit=n%10;
        if (digit==2 || digit==3 || digit==5 || digit==7)
            cout<<digit<<"and"<<endl;
        n=n/10;
    }
}

This produces one extra "and" at the ending that I don't want.

jhjhjh
  • 43
  • 3

2 Answers2

0

Instead of postfixing the and to every number except the last one you can instead prefix it to all except the first one. Determining the first number to be printed is trivial.

Salvage
  • 448
  • 1
  • 4
  • 13
0

Easier to print and before a prime digit, where you just skip the very first one using a flag:

    bool first = true;
    while (n>0)
    {
        digit=n%10;
        if (digit==2 || digit==3 || digit==5 || digit==7)
        {
            if (first) { cout << " and "; first=false;}
            cout<<digit;
        }
        n=n/10;
    }
    cout << endl;
Marc Stevens
  • 1,628
  • 1
  • 6
  • 16