int n;
cin >> n; cin.ignore();
for(int i = 1; i < 11; i++){
cout << i * n << " ";// stop printing space at the end number
}
Desired output-> "1 2 3 4 5 6 7 8 9 10"
int n;
cin >> n; cin.ignore();
for(int i = 1; i < 11; i++){
cout << i * n << " ";// stop printing space at the end number
}
Desired output-> "1 2 3 4 5 6 7 8 9 10"
The standard approach is to use a boolean variable, which is one time either true or false, then print a space or not, depending on the boolean, and set the boolen to a new value.
Often the output of the space in the loop is done first and then then value.
Example:
bool printSpace = false;
for(int i = 1; i < 11; ++i) {
if (printSpace) std::cout << ' ';
printSpace = true;
std::cout << i * n;
}
You could also use std::exchange
for flipping the bool. Please read here.
Then you could do something like the below:
#include <iostream>
#include <vector>
#include <utility>
int main() {
std::vector data{1,2,3,4};
bool showComma{};
for (const int i: data)
std::cout << (std::exchange(showComma, true) ? "," : "") << i;
}
And the super high sophisticated stuff will be done with the std::ostream_joiner
.
Reade here for an example. But, unfortunately this is not available for many installations.
A simple approach is the following
for( int i = 0; i < 10; i++){
if ( i ) cout << ' ';
cout << ( i + 1 ) * n;
}
or
for( int i = 1; i < 11; i++){
if ( i != 1 ) cout << ' ';
cout << i * n;
}
One-liner:
cout << (i > 1 ? " " : "") << i * n;
Note: I prefer the "prefix" form because the starting value is easier to know than the ending one (>1
vs. >9
).