Click here to Skip to main content
14,603,732 members
Rate this:
Please Sign up or sign in to vote.
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:

#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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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,
for (i=0; i<length; i++){

you need to reverse the order
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:
for (i=length-2; i>=0; i--){
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100