Are you familiar with functions? If not, it's a good time to start learning about
them. As pointed out by others above, breaking the task into smaller steps
helps a lot. So, let's focus on building a line first. Take a look at these lines:
122222221
123333321
123444321
There is a pattern here. Each one of them consists of a left, a middle and a right part,
where the right part is the left one reversed and the middle part is a repetition of the
same number. Let's write them again, so that this becomes more obvious:
1 - 2222222 - 1
12 - 33333 - 21
123 - 444 - 321
This line also follows the same pattern:
111111111
It just happens that the left and right parts are empty.
Now, let's write a function that builds a line like this...
string line(int n, int i)
{
// use the appropriate constructor to set the size for the left
// and right parts and properly initialize the middle part
string mid( /* ... */ );
string left( /* ... */ );
string right( /* ... */ );
// set the left and right parts
for (int j = 0; j < i - 1; ++j)
{
// remember that 1 + '0' == '1',
// 2 + '0' == '2', etc...
}
return left + mid + right;
}
Remember that we want …