Doupis
Doupis

Reputation: 35

C++ exclude part of loop operator on last loop

I am trying to figure out how to include a cout with a for loop that leaves off part of the cout on the last iteration. I want to have a multiplication sign (*) after each number (nFact) EXCEPT the last number in the loop.

Current output: 5*4*3*2*1* Ideal output: 5*4*3*2*1

'''

for (unsigned int i = 0; i < n; i++)
{
nFact = nFact*(n-i);
cout << (n - i)<<"*";
}

'''

Upvotes: 1

Views: 405

Answers (2)

Jarod42
Jarod42

Reputation: 217303

You might do:

const char* sep = "";
for (unsigned int i = 0; i < n; i++)
{
    nFact *= n - i;
    std::cout << sep << n - i;
    sep = "*";
}

Demo

Upvotes: 0

Maqcel
Maqcel

Reputation: 509

for (unsigned int i = 0; i < n; i++)
{
nFact = nFact*(n-i);
if(i!=n-1)
cout << (n - i)<<"*";
else  cout << (n - i);
}

Upvotes: 1

Related Questions