C++ creates various triangle patterns

 Article directory


foreword

After introducing C++, let's take a look at how to use C++ with an example.

1. Right triangle

Let's start with a simple triangle.

#include <iostream>
using namespace std;
 
int main()
{
    int rows;
 
    cout << "输入行数: ";
    cin >> rows;
 
    for(int i = 1; i <= rows; ++i)
    {
        for(int j = 1; j <= i; ++j)
        {
            cout << "* ";
        }
        cout << "\n";
    }
    return 0;
}

operation result:

*
* *
* * *
* * * *
* * * * *

2. Digital right triangle

Go ahead and make numbers.

#include <iostream>
using namespace std;
 
int main()
{
    int rows;
 
    cout << "输入行数: ";
    cin >> rows;
 
    for(int i = 1; i <= rows; ++i)
    {
        for(int j = 1; j <= i; ++j)
        {
            cout << j << " ";
        }
        cout << "\n";
    }
    return 0;
}

3. Letter right triangle

#include <iostream>
using namespace std;
 
int main()
{
    char input, alphabet = 'A';
 
    cout << "输入最后一个大写字母: ";
    cin >> input;
 
    for(int i = 1; i <= (input-'A'+1); ++i)
    {
        for(int j = 1; j <= i; ++j)
        {
            cout << alphabet << " ";
        }
        ++alphabet;
 
        cout << endl;
    }
    return 0;
}

4. Inverted right triangle 

#include <iostream>
using namespace std;
 
int main()
{
    int rows;
 
    cout << "输入行数: ";
    cin >> rows;
 
    for(int i = rows; i >= 1; --i)
    {
        for(int j = 1; j <= i; ++j)
        {
            cout << "* ";
        }
        cout << endl;
    }
    
    return 0;
}


Summarize

Have you learned the four types of triangle output?

There are no roads in the world, and when there are many people walking, it becomes a road. ——Lu Xun

Guess you like

Origin blog.csdn.net/we123aaa4567/article/details/128006325