This is my code:
#include <iostream>
using namespace std;
int main() {
int fib[10];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i < 10; i ) {
fib[i] = fib[i - 1] fib[i - 2];
}
for (int i = 0; i < 10; i ) {
cout << fib[i] << ", ";
}
return 0;
}
And this is the output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
But I want to replace the comma after 34 with a period. How would I do that?
CodePudding user response:
Change the print for loop to:
for (int i = 0; i < 10; i ) {
cout << fib[i] << (i < (10 - 1) ? ", " : ".");
}
CodePudding user response:
I like to handle it by printing the comma before the number rather than after it (except for the first number in the list) like this:
for (int i = 0; i < 10; i ) {
if (i > 0) cout << ", ";
cout << fib[i];
}
cout << ".";
CodePudding user response:
Branchless version:
const char* sep = "";
for (auto e : fib) {
std::cout << sep << e;
sep = ", ";
}
std::cout << ".";