Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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 << '
';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...