Solution Review: Printing C++

Learn to print the C++ pattern.

Printing C++

Write a program that prints C++:

Press + to interact
C++ segments
C++ segments

Look at the tables for each function below: ##The printS1_FirstAndLast() table printS1_FirstAndLast() function will print the first and last horizontal lines of length x. We need to call this function two times to print the first and last lines of the C++ pattern.

printS1_FirstAndLast()

Dashes(-)

Spaces

Spaces

Dashes(-)

Spaces

Spaces

Spaces

Dashes(-)

x

x/4

x/2

1

x/2

x/4

x/2

1

The printS2_Body() table

The printS2_Body()function will print the vertical lines (body segment) of the C++ pattern. We need to call this function x times.

printS2_Body()

Dashes(-)

Spaces

Spaces

Spaces

Dashes(-)

Spaces

Spaces

Spaces

Dashes(-)

1

x-1

x/4

x/2

1

x/2

x/4

x/2

1

TheprintS3_Middle() table

The printS3_Middle() function will print the middle segment of the C++ pattern.

printS3_Middle()

Dashes(-)

Spaces

Spaces

Dashes(-)

Dashes(-)

Dashes(-)

Spaces

Dashes(-)

Dashes(-)

Dashes(-)

1

x-1

x/4

x/2

1

x/2

x/4

x/2

1

x/2

We have called all three functions in PrintCPP().

Press + to interact
void PrintCPP(int x)
{
printS1_FirstAndLast(x); // First line of
for(int i=1; i<=x; i++)
printS2_Body(x); // Vertical lines
printS3_Middle(x); // Middle horizontal line
for(int i=1; i<=x; i++)
printS2_Body(x); // Vertical lines
printS1_FirstAndLast(x); // Last line
}

Solution

Let’s take a look at the solution.

Press + to interact
#include <iostream>
using namespace std;
void printASymbolKTimes(char s, int k)
{
for(int t=1; t<=k; t++)
cout << s;
}
void printS1_FirstAndLast(int x)
{
printASymbolKTimes('-', x);
printASymbolKTimes(' ', x/4);
printASymbolKTimes(' ', x/2);
cout << "-";
printASymbolKTimes(' ', x/2);
printASymbolKTimes(' ', x/4);
printASymbolKTimes(' ', x/2);
cout << "-";
cout << endl;
}
void printS2_Body(int x)
{
cout << "-";
printASymbolKTimes(' ', x-1);
printASymbolKTimes(' ', x/4);
printASymbolKTimes(' ', x/2);
cout << "-";
printASymbolKTimes(' ', x/2);
printASymbolKTimes(' ', x/4);
printASymbolKTimes(' ', x/2);
cout << "-";
cout<<endl;
}
void printS3_Middle(int x)
{
cout << "-";
printASymbolKTimes(' ', x-1);
printASymbolKTimes(' ', x/4);
printASymbolKTimes('-', x/2);
printASymbolKTimes('-', 1);
printASymbolKTimes('-', x/2);
printASymbolKTimes(' ', x/4);
printASymbolKTimes('-', x/2);
printASymbolKTimes('-', 1);
printASymbolKTimes('-', x/2);
cout << endl;
}
void PrintCPP(int x)
{
printS1_FirstAndLast(x); // printing the 1st segment
for(int i=1; i<=x; i++) // printing the 2st segment
printS2_Body(x);
printS3_Middle(x); // printing the middle segment line
for(int i=1; i<=x; i++) // printing the 2nd segment again
printS2_Body(x);
printS1_FirstAndLast(x); // printing the 1st segment
}
int main()
{
PrintCPP(10);
return 0;
}