-3

So, my friend's program is supposed to find the Multiplicative of Number three then print them out with a comma between the number. And not for the last one.

int a;
int b;

cout<< "First Number = ";
cin>>a;
cout<< "Last Number = ";
cin>>b;

if(a<=b)
{
    for(a;a<=b;a++)
    {
        if(a%3 == 0 && a%2 != 0)
        {   
            cout<<a;
        }
        if(a<b && a%3==0 && a%2 != 0)
        {
            cout<< " , ";
        }
        else if(a==b)
        {
            cout<< ".";
        }
    }
}

And after i input

a = 1

b = 20

this is what i expected

3 , 9 , 15.

and this is what i actually get

3 , 9 , 15 , .

dbc
  • 104,963
  • 20
  • 228
  • 340
FcIp3
  • 1
  • 1

1 Answers1

1

I would do something like this:

char const* sep = ""; // item separator (nothing to begin with)

for(a;a<=b;a++)
{
    if(a%3 == 0 && a%2 != 0)
    {   
        cout << sep << a; // output the separator before the next value
        sep = ", "; // now change it to a comma
    }
}

cout << "."; // finish with a full stop
Galik
  • 47,303
  • 4
  • 80
  • 117
  • it gives me "Error 'sep' does not name a type" and "Error 'sep' was not declared in this scope" – FcIp3 Nov 04 '17 at 05:49
  • @FcIp3 perhaps you are using an older version of the standard. I edited the code so it should hopefully work now. – Galik Nov 04 '17 at 05:51