Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

how to create a pyramid using for loop in c++

Hello guys I just want to ask how can I create a triangle using c++?

Actually I have my code but I don't have an idea how to center the first asterisk in the triangle. My triangle is left align. How can I make it a pyramid?

Here's my code below.

#include<iostream>
using namespace std;

int main(){

    int x,y;
    char star = '*';
    char space = ' p ';
    int temp;   

    for(x=1; x <= 23; x++){ 

        if((x%2) != 0){

            for(y=1; y <= x ; y++){     

                cout << star;
            }

            cout << endl;           
        }       
    }

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For a triangle och height Y, then first print Y-1 spaces, followed by an asterisk and a newline. Then for the next line print Y-2 spaces, followed by three asterisks (two more than previously printed) and a newline. For the third line print Y-3 spaces followed by five asterisks (again two more than previous line) and a newline. Continue until you have printed your whole triangle.

Something like the following

int asterisks = 1;
for (int y = HEIGHT; y > 0; --y, asterisks += 2)
{
    for (int s = y - 1; s >= 0; --s)
        std::cout << ' ';

    for (int a = 0; a < asterisks; ++a)
        std::cout << '*';

    std::cout << '
';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...