Click here to Skip to main content
15,895,777 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm struggling to find out how to make it so the second triangle is upside down, I think
I understand the concept of how to do it (Just do a regular triangle's code but in reverse) but I'm struggling with the execution. Any help would be greatly appreciated as I'm relatively new to c++.

What the code prints is this:
     
              S
             SAS
            SAMAS
           SAMPMAS
          SAMPLPMAS
         SAMPLELPMAS
              S
             SAS
            SAMAS
           SAMPMAS
          SAMPLPMAS
         SAMPLELPMAS

When it's supposed to print this:
`````
              S
             SAS
            SAMAS
           SAMPMAS
          SAMPLPMAS
         SAMPLELPMAS
          SAMPLPMAS
           SAMPMAS
            SAMAS
             SAS
              S


What I have tried:

C++
#include <iostream>

using namespace std;
int main(){

string word;
int length, i, j;
cout<<"Enter a word: ";
cin>>word;

length=word.size();
if (word.size()>10){
    length=10;
}

for (i=0; i<length; i++){
    for (j=length-1-i; j>0; j--){
        cout<<" ";
    }
    for (j=0; j<=i; j++){
       cout<<word[j];
    }
    
    for (j=i-1;j>=0; j--){
        cout<<word[j];
    }
    
    cout<<endl;
}

for (i=0; i<length; i++){
    for (j=length-1-i; j>0; j--){ 
        cout<<" ";
    }

    for (j=0; j<=i; j++){ 
       cout<<word[j];
    }
   
    for (j=i-1;j>=0; j--){ 
        cout<<word[j];
    }
  
    cout<<endl;
}

return 0;
}
Posted
Updated 25-May-20 20:27pm
v2

1 solution

Quote:
I understand the concept of how to do it (Just do a regular triangle's code but in reverse) but I'm struggling with the execution.

In second part,
C++
for (i=0; i<length; i++){

you need to reverse the order
C++
for (i=length-1; i>=0; i--){

[Update]
Quote:
It worked but now the middle line happens twice, any way to fix this?

Then remove 1 to first value:
C++
for (i=length-2; i>=0; i--){
 
Share this answer
 
v3
Comments
Member 14843505 25-May-20 20:40pm    
It worked but now the middle line happens twice, any way to fix this?
Rick York 26-May-20 18:47pm    
Of course there is. It's your homework though so it would be best if you fix it.
CPallini 26-May-20 2:12am    
5.
Patrice T 26-May-20 2:46am    
Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900