String Triangle

The below code displays:
c
co
com
comp
compu
comput
compute
computer

But I'm trying to make it display:

r
er
ter
uter
puter
mputer
omputer
computer

I can make it display the same kind of way pointing down but can't get it pointing up.

1
2
3
4
5
6
7
8
9
10
11
12
13
//sample code

string word = "computer";

if (word == "computer"){

  for (int i= 0; i < word.length(); i++){
        for (int j = 0; j <= i; j++){
          cout << word[j]; // printing triangle to console
        }
        cout << "\n";
      }
}
Last edited on
Try using an array and initializing it with the letters, and then print them in reverse order.
do you have any example? cause Im just printing them in reverse order like

r
re
ret
retu
retup
retupm
retupmo
retupmoc
Hello libi,

Printing it somewhat backwards is a bit tricky. The inner for loop can not start at zero like you have, but at "word.size() - 1". Then this has to change each time through the outer for loop. This can be done either in the outer for loop condition or at the bottom of the outer for loop.

I have tested this and it works:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
std::string word = "computer";
int start{};

if (word == "computer")
{
	start = word.size();
	start--;  // <--- equals word length - 1.

	for (int i = 0; i < word.length(); i++, start--)
	{
		for (int j = start; j < word.size(); j++)
		{
			std::cout << word[j]; // printing triangle to console
		}

		std::cout << "\n";
		//start--;
	}
}

"word.size()" is the same as "word.length()".

Hope this helps,

Andy
Ohh I see how you did it, thank you!
Topic archived. No new replies allowed.