Challenge: Printing C++

Test your problem-solving skills in this challenging C++ printing exercise.

Print C++ using nested loops

In this lesson, we have a printing C++ challenge for you.

Challenge

Your code should print the following shape based on a parameter x.

Implementation directions

If you look closely, the pattern has five segments as shown below:

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

The first and fifth segments are the same. Similarly, the second and fourth segments are the same too. The third part in the middle is unique and, so, is separated. We will write each segment separately.

In a nutshell, the drawing has the following steps:

void PrintCPP(int x)
{
   // STEP 1: Print Segment 1
   // STEP 2: Print Segment 2
   // STEP 3: Print Segment 3
   // STEP 4: Print Segment 2
   // STEP 5: Print Segment 1
}

Segment 1: The first and last lines

If you look closely at the first and last lines, they are the same. They have the following configuration:

  • Print x dashes.
  • This is followed by x/4 and x/2 spaces.
  • A symbol '-'
  • This is followed by x/2, x/4 and x/2 spaces.
  • A symbol '-'
  • This is followed by x/2 spaces (not needed though).
void printS1_FirstAndLast(int x)
{
   printASymbolKTimes('-', x);
   printASymbolKTimes(' ',x/4);
   printASymbolKTimes(' ',x/2);
   printASymbolKTimes('-',1);
   printASymbolKTimes(' ',x/2+x/4+x/2);
   printASymbolKTimes('-',1);
   printASymbolKTimes(' ',x/2); // does not need it
   cout << endl;
}

Instruction: Write your code in the playground below.

Exercise: Solve the rest

Figure out the rest of the segments on your own by following the segmented pictures below:

Playground

Write your final code here by following the above directions.

Press + to interact
#include <iostream>
using namespace std;
void printS1_FirstAndLast(int x);
void printS2_Body(int x);
void printS3_Middle(int x);
void printASymbolKTimes(char s, int k)
{
for(int t=1; t<=k; t++)
cout << s;
}
void printS1_FirstAndLast(int x)
{
// Write code here
}
void printS2_Body(int x)
{
// Write code here
}
void printS3_Middle(int x)
{
// Write code here
}
void PrintCPP(int x)
{
//Write your code here
}