Triangles

Mar 11, 2017 at 1:51am
hi guys , just wondering if you can help in printing out a right triangle , but with words. Also using the .length in the equation . Please show me using c++
Last edited on Mar 11, 2017 at 2:13am
Mar 11, 2017 at 1:53am
Sorry, I'm a little confused by what you're asking. Do you have anything you've already tried that I could see?
Mar 11, 2017 at 2:09am
OP: also do a quick search on 'triangle(s)' through the search-box above, if you haven't done so already. this is quite a popular topic and pops up regularly
Mar 11, 2017 at 4:55pm
So this is the triangle printed with stars :
{
For (int bottom = 1; bottom <= width ; bottom ++)
{
For (int count = 1 ; count <= bottom ; count++ )
{
Cout<< '*' ;
}
cout<< ends;
}

}

*
**
***
****.
Just wondering if you can show me how to print a right triangle with string.length in which setting it up.
I tried using the c++ search engine , but no similar topics appeared. Printing triangle with any word .

HELP
ELP
LP
P

and

P
LP
ELP
HELP


Last edited on Mar 11, 2017 at 4:59pm
Mar 11, 2017 at 6:11pm
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

int main()
{
    std::string myString = "ComeOnArsenal!";
    for (size_t i = 0; i < myString.size(); ++i)
    {
        std::cout.write(&myString[0], myString.size()-i);
        //http://en.cppreference.com/w/cpp/io/basic_ostream/write
        std::cout << "\n";
    }
}
edit: strings with spaces within them will appear as if the same substring has been printed twice, it's actually two different substrings, one with the space at the back and one without. if this is of interest have a go how you might skirt this issue
Last edited on Mar 11, 2017 at 6:15pm
Mar 12, 2017 at 11:21pm
thank you @gunnerfunner. i got the idea of the string but i printed the triangle by the incorrect order. can you help me fix it or anyone. please help.

my work:

cout << " Please insert a word " << endl;
cin >> word;
int length = word.length();

cout << " Is the triangle 1) up or 2) down " << endl;
cout << " 1 or 2"<<endl;
cin >> choice;

if (choice == 1)
{ // up triangle
for(int i = 0; i <= word.length(); i++)
{
for (int a = 0; a < i; a++)
{
cout << word[a];
}
cout << endl;
}


}
else if (choice == 2)
{ // down triangle
for (int i = length; i >= 0; i--)
{
for (int a = 0; a < i; a++)
{
cout << word[a];
}
cout << endl;
}
}

H
HE
HEL
HELP


HELP
HEL
HE
H
i want the triangles printd as:
HELP
ELP
LP
P

P
LP
ELP
HELP


Last edited on Mar 12, 2017 at 11:25pm
Mar 13, 2017 at 2:15am
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

int main()
{
    std::string myString = "ComeOnArsenal!";
    for (size_t i = 0; i < myString.size(); ++i)
    {
        std::cout.write(&myString[i], myString.size()-i);
        //http://en.cppreference.com/w/cpp/io/basic_ostream/write
        std::cout << "\n";
    }
}
Topic archived. No new replies allowed.