Solution Review: Printing C++
Learn to print the C++ pattern.
We'll cover the following
Printing C++
Write a program that prints C++:
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()
.
void PrintCPP(int x){printS1_FirstAndLast(x); // First line offor(int i=1; i<=x; i++)printS2_Body(x); // Vertical linesprintS3_Middle(x); // Middle horizontal linefor(int i=1; i<=x; i++)printS2_Body(x); // Vertical linesprintS1_FirstAndLast(x); // Last line}
Solution
Let’s take a look at the solution.
#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 segmentfor(int i=1; i<=x; i++) // printing the 2st segmentprintS2_Body(x);printS3_Middle(x); // printing the middle segment linefor(int i=1; i<=x; i++) // printing the 2nd segment againprintS2_Body(x);printS1_FirstAndLast(x); // printing the 1st segment}int main(){PrintCPP(10);return 0;}