4

LANGUAGE: C++ Hello, in the following function (code block) i have written a line to print an space between characters but i don't want print spaces after last characters. How can i solve this problem?

bool perfecto(int n) { int suma, i; suma = 0; for (i = 1; i < n; i++) { if (n % i == 0) { suma += i; cout << i << " "; } } if (suma == n) return true; else return false; } 

Best regards. Ángel Manuel.

1

5 Answers 5

16

The simplest way would be to turn the problem around: if you only print spaces before printing the number (and not after) then it becomes how not to print the first time, which is much easier.

I'll let you figure it out :)

Sign up to request clarification or add additional context in comments.

Comments

4
bool perfecto(int n) { int suma, i; suma = 0; bool first = true; for (i = 1; i < n; i++) { if (n % i == 0) { suma += i; if ( !first ) { cout << " "; } cout << i; first = false; } } if (suma == n) return true; else return false; } 

Comments

0

You can either check if i is equal to n - 1 and not print it in that case, or something like

std::cout << "1"; for (int i = 2; i < n; ++i) { std::cout << " " << i; } 

In the second case, you have to watch for for a case where n is 1 or less

1 Comment

He isn't printing all numbers, just the factors.
0

There are a variety of options. In this case, probably the easiest is to print spaces BEFORE elements except the first and use a flag to track the first element:

bool perfecto(int n) { int suma, i; suma = 0; bool first = true; for (i = 1; i < n; i++) { if (n % i == 0) { suma += i; if(!first) { std::cout << " "; } else first = false; cout << i; } } if (suma == n) return true; else return false; } 

EDIT: Other popular alternatives are printing the first item and no delimiter outside the loop completely and then inside the loop you can always pre-print the item with no if-check at all. This approach wouldn't work as well with your loop though since you don't always know when the first item will print. You can also create wrapper ostream like classes that keep track of their internal printing state and know when to put the spaces.

1 Comment

In these cases, instead of having a bool and an if statement, I like to have a char * space = "" before the loop, and then at the end of the loop put space = " ". It may make a tiny performance difference or none at all, but I think it's more readable.
-2

Replace this line: cout << i << " "; with:

cout << i; if (i == n-1) cout << endl; else cout << " "; 

1 Comment

Counter-example: n = 6, output is 1 2 3 . Your code doesn't eliminate the trailing space.