I have to write a C++ program to print this pattern:
* *
* * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
This is the solution I have:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
for(int i = 1; i <= 5; ++i) {
string temp = "";
for(int j = 1; j <= i; ++j) {
if(j == i)
temp += "*";
else
temp += "* ";
}
cout << left << setw(10)<< temp;
cout << right << setw(10) << temp << endl;
}
return 0;
}
Is there a solution using just simple spaces? Don't just write the five strings in the cout
statements.
You can do this easily, if you use two string variables, eg left
and right
, instead of your single temp
variable:
for(int i = 0; i < 5; i++)
{
string left, right;
for(int j = 0; j < 5; j++)
{
if(j - i < 1)
{
// Add a star and a space to each side.
left += "* ";
right = " *" + right;
}
else
{
// Add four spaces into the middle between the stars.
left += " ";
}
}
cout << left + right << endl;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.