ICS2O Grade 10 Computer Science – Printing “Triangle” Letters

Full source available below.

This note is to answer a common beginners computer science question:

“Write a program to print out a word in a triangle of different sorts”

I’ve created C++ code to print out an input phrase in various ways. C++ code can easily be ported over to Java, VBA, or Python code.

1) Print in left right angle

N
NO
NOT
NOTE
NOTES

Code:

void leftAngle(string phrase) {
   for (int x = 0; x < phrase.length()+1; ++x) {
      cout << phrase[y];
   }
   cout << endl;
   }
}

2) Print in right right angle

    S
   ES
  TES
 OTES
NOTES

Code:

void rightAngle(string phrase) {
   int spaceLength = (int)phrase.length();
   int wordIndex = (int)phrase.length();
   for (int x = 0; x < phrase.length(); ++x) {
      for (int y = spaceLength; y > 0; --y) {
         cout << " ";
      }
      for (int y = wordIndex; y < phrase.length(); ++y) {
         cout << phrase[y];
      }
      --spaceLength;
      --wordLength;
      cout << endl;
   }
}

3) Print Equilateral Triangle

    N
   N O 
  N O T
 N O T E
N O T E S

Code

void equilateralAngle(string phrase) {
   int numberOfSpaces = (int)phrase.length()-1;
   int wordLength = 1;
   for (int x = 0; x < phrase.length(); ++x) {
      for (int y = 0; y < numberOfSpaces; ++y) {
         cout << " ";
      for (int y = 0; y < wordLength; ++y) {
         cout << phrase[y] << " ";
      }
      cout << endl;
      ++wordLength;
      --numberOfSpaces;
   }
 }

I’ve included the full source code which also includes upside down versions of these triangles and an I/O main function to gather input.

DOWNLOAD FULL SOURCE HERE (.cpp) file.