Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
when i input
a = 1
b = 20

my output is always :
"3 , 9 , 15 , ."

but what i wanted is :
"3 , 9 , 15."

PS : SOrry for my bad english, i hope you guys understand
i just need an example or solution to this program

What I have tried:

int a,b;

cout<< "Number 1 = ";
cin>>a;
cout<< "Number 2 = ";
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<< ".";
        }
Posted
Updated 3-Nov-17 20:51pm
v3
Comments
enhzflep 5-Nov-17 2:06am    
While i see you've already reached a solution, there is another way to think about the problem.
No one I've met actually puts commas _after_ numbers when writing them in a list. What they do is put commas _before_ numbers that aren't the first in a list.

So, if you consider a for loop that prints out the value of the loop counter, the way you do it is to print a comma before the number, provided the loop counter doesnt hold its initial value. Once all the numbers have been printed, spit-out a full-stop and you're done.

My code improved once i looked at the problem from this different perspective. :)

You could write the if-else logic like this :
C++
if( ( a % 3 == 0 ) && ( a % 2 != 0 ) )
{
    cout << a;
    if( a == b )
        cout << ".";
    else
        cout << " , ";
}
 
Share this answer
 
v2
First, a little analyze:
The '.' will be always printed and always be last. Which means simplification
C++
if(a<=b)
{
    for(a;a<=b;a++)
    {
        if(a%3==0&&a%2!=0)
        {
            cout<<a;
            if(a<b)
            {
                cout<< " , ";
            }
        }
    }
    cout<< ".";
}

The problem in your code is that b will not necessary be printed.
There is many solution around this
- if you print the comma after a number, you need to make sure there will be a next number to print.
- if toy print the comma before a number, you need to make sure it is not the first.
 
Share this answer
 
Thanks guys but i already got my solution to put

char const*sep = ""

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

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900