简体   繁体   中英

How to make word triangle in c++ with for loop

how can I make this type of triangle: where the size of triangle n = 5;

Five Four Three Two One
Five Four Three Two
Five Four Three
Five Four
Five

Here's what I've tried:

int n;
cout<<"Enter Size of triangle: ";
cin>>n;

for(int i = n; i >= 1; i--){
    for(int j = n; j >= i; j--){
        cout<<j<<" ";
    }
    cout<<endl;
}
for(int i = n; i >= 1; i--){
    for(int j = n; j >= i; j--){
        switch(j) {
            case 0: cout <<"zero"<<; break;
            case 1: cout <<"one"<<; break;
            case 2: cout <<"two"<<; break;
            case 3: cout <<"three"<<; break;
        }
    }
    cout<<endl;
}

I suppose you can get the loop right yourself, so what is left is map numbers to strings. There is no automatic way to do that, but you have to define this mapping yourself. Perhaps the easiest is to use a

std::vector<std::string> numbers{ "One", "Two", "Three", "Four", "put" ,"more", "numbers", "here" };

And then instead of printing the number j you print numbers[j] . Just take care of indexing: Vector uses zero-based indexing, but the first element is "One" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM